0% found this document useful (0 votes)
6 views

7

This document provides an overview of I/O streams in Java, focusing on file reading and writing using BufferedWriter and BufferedReader classes. It explains the concepts of relative and absolute paths, how to use BufferedWriter to write data to files, and how to use BufferedReader to read data from files. Additionally, it highlights key methods and exceptions associated with these classes, along with sample code for practical understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

7

This document provides an overview of I/O streams in Java, focusing on file reading and writing using BufferedWriter and BufferedReader classes. It explains the concepts of relative and absolute paths, how to use BufferedWriter to write data to files, and how to use BufferedReader to read data from files. Additionally, it highlights key methods and exceptions associated with these classes, along with sample code for practical understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

I/O Streams

Concepts
Paths

BufferedWriter

BufferedReader

Introduction

In Java, we can read and write data from one file to another file. Working with files
is an important skill, as it allows us to read data from external sources and write data
to a persistent storage. This is useful for a variety of applications, including:

Reading configuration files to customize the behavior of our application


Reading data from an external storage system
Saving data to a persistent storage system
Generating reports or other output files

In this unit, we'll learn various classes and methods in Java to read and write data in
files.

1. Paths

In Java, the
Path interface from java.nio.file package represents a path to a file or
directory in the file system. It provides a way to manipulate files and directories in a
platform-independent manner, which means we can use the same code to work with
files and directories on different operating systems.

The paths are of two types:

1. Relative path
2. Absolute path

1. Relative Path

A relative path is a path that specifies the location of a file or directory relative to the
current working directory.

For example, a relative path might be something like

documents\file.txt , which specifies the location of the file file.txt in the


documents folder in the current working directory.

2. Absolute Path

An absolute path is a path that specifies the exact location of a file or directory in the
file system, starting from the root directory.

For example, on a Unix-based system, an absolute path might be something like

/home/rahul/documents/file.txt , which specifies the location of the file file.txt in


the Documents folder of the user Rahul. On a Windows system, an absolute path
might be something like C:\users\rahul\documents\file.txt , which specifies the
same location on the C: drive.

Finding Absolute Path using Java

The

getAbsolutePath() method is used to get the absolute path of a file.

Syntax
JAVA

1 file.getAbsolutePath();
Code
JAVA

1 import java.io.File;
2
3 class Main {
4 public static void main(String args
5 File file = new File("file.txt"
6 String absolutePath = file.getA
7
8 System.out.println(absolutePath
9 }
10 }

Sample Output

/home/rahul/documents/file.txt

In the above code, we created a file object using the path as

file.txt and called the getAbsolutePath() method. Here, it points to the file
present in the same directory where the program is being executed.

2. BufferedWriter

The

BufferedWriter is a class from the java.io package that extends the abstract
class Writer . The BufferedWriter buffers characters to provide for the efficient
writing of single characters, arrays, and strings. The Writer writes text to a
character-output stream.
We can assume the buffer as a temporary storage area that is used to hold data before
it is written to the character-output stream (the actual data that is written to the file).
The

BufferedWriter maintains an internal buffer of 8192 characters. However, we can


increase its size by specifying it as the second argument to the constructor of
BufferedWriter .

As the first argument, it accepts a

Writer type. But we cannot instantiate Writer as it is an abstract class. Instead,


we can provide an object of the FileWriter class that extends the Writer class.

The constructor of

FileWriter accepts the file name (String) as an argument and returns a


FileWriter object.

The

FileWriter throws an IOException in case the provided file name is actually a


directory or the file cannot be accessed or created. So, we need to handle the
exception too.

Syntax
JAVA

1 BufferedWriter buffer = new BufferedWrit

Here,

Writer : is the Writer type object.


size (optional): is the size of int type, to specify the size of the buffer.

Code
JAVA

1 import java.io.BufferedWriter;
2 import java.io.FileWriter;
3 import java.io.IOException;
4
5 class Main {
6 public static void main(String[]
7 try {
8 BufferedWriter buffer =
9 } catch (IOException e) {
9 } catch (IOException e) {
10 System.out.println(e.getM
11 }
Expand

In the above code, we have tried to create a

BufferedWriter object with a relative path of the file. It searches for the file
destination.txt in the current directory (in which the program is executed) and
creates a writer object. If the file is not found, it creates a new file.

Now, let's write something to the file.

2.1 Writing Data to a File

Writing data to a file with

BufferedWriter starts with the creation of a buffer of the characters, writing


characters to the buffer, then writing the data to the character-output stream which is
the actual data that is written to the destination file.

We can use the

write() method to write data to the buffer. When the buffer is full or when the
flush() or close() method is called, the data in the buffer is written to the
character-output stream and the buffer is emptied.

Example 1: Writing a single line of string to the file

Code
JAVA

1 import java.io.BufferedWriter;
2 import java.io.FileWriter;
3 import java.io.IOException;
4
5 class Main {
6 public static void main(String[]
7 try {
8 BufferedWriter buffer =
9 buffer.write("Writing to
10 buffer.close(); // close
11 } catch (IOException e) {
Expand

Text in the destination.txt file


Writing to a file using BufferedWriter

In the above code, we have accessed the previously created file, written some text to
the buffer, and closed the bufferwriter with

close() method.

Once the

close() method is called, we cannot use the writer to write the data.

Example 2: Writing data from an array

Code
JAVA

1 import java.io.BufferedWriter;
2 import java.io.FileWriter;
3 import java.io.IOException;
4 import java.util.Arrays;
5
6 class Main {
7 public static void main(String[]
8 int[] numbers = {1, 2, 3, 4,
9 try {
10 BufferedWriter bw = new
11 for (int number : number
Expand

Text in the destination.txt file

1
2
3
4
5

In the above code, as the


write() method accepts String type as an argument we have converted
numbers to the string. To get each number on a new line we have used the newline
character \n at the end of each number while writing the data to the buffer.

We can notice that the previous text in the

destination.txt file is overwritten with the new data. This is because the
FileWriter as a default opens the existing file or creates a new one with
truncate (remove) mode. It removes any existing contents of the file.

If we want to append new data to the end of an existing file instead of overwriting it,
we can pass the

true value as the second argument to the FileWriter constructor. This will
open the file in append mode, which means that new data will be added to the end
of the file, rather than replacing the existing contents.

Syntax
JAVA

1 BufferedWriter buffer = new BufferedWrit

Other Methods

Method Description

newLine() Writes a line separator.

write(char[] cbuf, int


Writes a portion of an array of characters.
off, int len)
write(String s, int off,
Writes a portion of a String.
int len)
Flushes the contents of internal buffer to
flush()
the character-output stream.

3. BufferedReader
The

BufferedReader is a class from the java.io package extends the abstract class
Reader .

Similar to the

BufferedWriter , the BufferedReader maintains an internal buffer of 8192


characters. However, we can increase its size by specifying it as the second
argument to the constructor of BufferedReader .

As the first argument, it accepts a

Reader type. But we cannot instantiate Reader as it is an abstract class.


Instead, we can provide an object of the FileReader class that extends the
Reader class.

The

FileReader throws a FileNotFoundException in case the provided file name is


actually a directory or the file cannot be accessed. So, we need to handle the
exception too.

Syntax
JAVA

1 BufferedReader bufferReader = new Buffer

Here,

Reader : is the Reader type object.


size (optional): is the size of int type, to specify the size of the buffer.

Code
JAVA

1 import java.io.BufferedReader;
2 import java.io.FileReader;
3 import java.io.FileNotFoundException
4
5 class Main {
6 public static void main(String[]
7 try {
8 BufferedReader buffer =
9 } catch (FileNotFoundExceptio
10 System.out.println(e.getM
}
11 }
Expand

In the above code, we have tried to create a

BufferedReader object with a relative path of the file. It searches for the file
source.txt in the current directory (in which the program is executed) and creates
a writer object. If the file is not found, it throws an exception.

Now, let's read data from a file.

3.1 Reading Data from a File

The

BufferedReader uses the Reader object to read data from a file and it stores
the data in an internal buffer.

The

BufferedReader provides various methods to read data from a file:

1. read()
2. readLine()

Similar to

BufferedWriter , the BufferedReader also has a close() method which


closes the stream and releases any system resources associated with it.

1. read()

The

read() method reads a single character from a file. It returns int data type.

Example 1: Reading a single character from the file and writing it to another file

Code
JAVA

1 import java.io.*;
2
3 class Main {
4 public static void main(String[]
5 try {
6 BufferedReader br = new
7 BufferedWriter bw new
7 BufferedWriter bw = new
8
9 int data = br.read();
10 bw.write(data);
11 br.close();
Expand

Text in the source.txt file

Hello World!

Text in the destination.txt file

In the above code, we are creating a

BufferedReader object br to read from a file called source.txt . We are also


creating a BufferedWriter object bw to write to a file called destination.txt .
Then, we use the read() method of the BufferedReader object to read a single
character from the file source.txt and store it in the variable data .

Finally, we use the

write() method of the BufferedWriter object to write the character stored in


data to the file destination.txt . We close both the BufferedReader and
BufferedWriter objects at the end of the code block.

Example 2: Reading characters from a file and storing them in an array

Code
JAVA

1 import java.io.*;
2
3 class Main {
4 public static void main(String[]
5 try {
6 BufferedReader br = new
7 char[] arr = new char[100
8
9 br.read(arr);
10 System.out.println(arr);
11 br.close();
Expand

Text in the source.txt file

Hello World!

Output

Hello World!

In the above code, we are reading a text file

source.txt using the BufferedReader class. We have created an array of


characters arr and passed it to the read() method of the BufferedReader
object. The read() method reads the characters from the source.txt file and
stores them in the arr array.

Finally, we have displayed the array on the console using

System.out.println(arr) , which displays the contents of the source.txt file.

Note

The System.out.println() method accepts a char array char[] as an


argument and prints the characters to the console.

2. readLine()

The
readLine() method is used to read a single line of text in the file. It returns
String data type.

Let's read a single line of text from the

source.txt file and write it to the destination.txt file.

Code
JAVA

1 import java.io.*;
2
3 class Main {
4 public static void main(String[]
5 try {
6 BufferedReader br = new
7 BufferedWriter bw = new
8
9 String line = br.readLine
10 bw.write(line);
11 br.close();
Expand

Text in the source.txt file

Hello World!
This is the second line.

Text in the destination.txt file

Hello World!

In the above code, the

readLine() method reads a line of text from the file and returns it as a string. We
then used the BufferedWriter class to write this line of text to the file
destination.txt . The write() method writes the specified string to the file.

Finally, we close both the


BufferedReader and BufferedWriter objects to release system resources.

Now that we have learned to read and write a specific length of content from the file.
Let's write a code that reads a whole file and writes it to another file.

Code
JAVA

1 import java.io.*;
2
3 class Main {
4 public static void main(String[]
5 try {
6 BufferedReader br = new
7 BufferedWriter bw = new
8
9 String line;
10 while ((line = br.readLi
11 bw.write(line);
Expand

Text in the source.txt file

Hello World!
This is the second line.

Text in the destination.txt file

Hello World!
This is the second line.

In the above code, we are reading the

source.txt file line by line using the readLine() method of the


BufferedReader class. The readLine() method reads a line of text and returns
it as a String . The write() method of the BufferedWriter class writes the
line to the destination.txt file. The newLine() method is used to write a
newline character to the file.
The loop continues until the

readLine() method returns null , which indicates the end of the file. Finally, we
close the BufferedReader and BufferedWriter objects to release the resources.

Other Methods

Method Description

skip(long n) Skips characters

ready() Checks if the file reader is ready to be read

Summary

Paths

Relative path: A relative path is a path that specifies the location of a


file or directory relative to the current working directory.

Absolute path: An absolute path is a path that specifies the exact


location of a file or directory in the file system, starting from the root
directory.

BufferedWriter

The FileWriter creates a new file if the specified file is not found.

The write() method overwrites the contents of a file by default.


However, we can specify to overwrite or append the content to the file.

BufferedReader

The FileReader throws an exception if the specified file is not found.

The read() method reads a single character from the file.

The readLine() method reads a single line from the file.

The readLine() method returns null at the end of the file.

You might also like