Java file BufferedWriter


 

Java file BufferedWriter

This section demonstrates you the use of BufferedWriter class.

This section demonstrates you the use of BufferedWriter class.

Java file BufferedWriter

This section demonstrates you the use of BufferedWriter class.

The BufferedWriter is a character stream class which allows to write the strings, arrays or characters data directly to the file. It provides buffering to the Writer. Using this class you can write a larger block at a time rather than write one character at a time to the network or disk. It is much faster, especially for disk access and larger data amounts.

In the given example, we have allowed the user to enter the data to be stored into the file. As the user writes the data on the console, InputStream reads the data from it. This data is then stored into the file using the method write() of BufferedWriter class.

read(): This method of InputStream class reads the next byte of data from the input stream.

write(int ch): This method of BufferedWriter class write a single character.

flush(): This method of BufferedWriter class flushes the stream.

Here is the code:

import java.io.*;

public class FileBufferedWriter {
	public static void main(String[] args) throws Exception {
		System.out.println("Enter text to store in the file:");
		InputStream in = System.in;
		BufferedWriter bw = new BufferedWriter(new FileWriter("C:/output.txt"));
		int i;
		while ((i = in.read()) != -1) {
			bw.write((char) i);
			bw.flush();
		}
	}
}

Ads