HudaTutorials.com

Java BufferedWriter Class

Last updated on

java.io.BufferedWriter Class

BufferedWriter Class in Java

The BufferedWriter is a Writer that buffers output, writes text to a character output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. Using a BufferedWriter can improve performance by reducing the number of times data is actually physically written to the output device.

Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.

A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.

What is BufferedWriter in Java ?

The BufferedWriter is a Java class that writes text to a character output stream, while buffering characters so as to provide for the efficient writing of single characters, strings and arrays. java.io package contains the BufferedWriter class.

BufferedWriter Constructors

  • BufferedWriter(Writer out) : Creates a buffered character output stream that uses a default sized output buffer.
  • BufferedWriter(Writer out, int size) : Creates a new buffered character output stream that uses an output buffer of the given size.

BufferedWriter Methods

  • write(int arg) : java.io.BufferedWriter.write(int arg) method writes a single character that is specified by an integer argument to BufferedWriter.
  • write(String arg, int offset, int length) : java.io.BufferedWriter.write(String arg, int offset, int length) method writes String to BufferedWriter.
  • newLine() : java.io.BufferedWriter.newLine() method writes new line character to BufferedWriter.
  • flush() : java.io.BufferedWriter.flush() method flushes characters from write buffer of BufferedWriter.
  • close() : java.io.BufferedWriter.close() method flushes characters from write buffer and close the BufferedWriter.

How to write String to console

The following program shows how to send output to console using java.

/*	How to write String to console Example
	Save with file name BufferedWriterExample.java	*/
import java.io.*;
public class BufferedWriterExample
{
	public static void main(String args[])
	{
		// java.io.BufferedWriter DECLARATION
		java.io.BufferedWriter bw = null;
		// OutputStreamWriter DECLARATION
		OutputStreamWriter osw = null;
		// WE SHOULD USE try-catch BECAUSE MOST OF THE
		// JAVA I/O CLASES THROWS IOException
		try
		{
			String str = "This is test String for BufferedWriter.";
			osw = new OutputStreamWriter(System.out);
			bw = new BufferedWriter(osw);
			bw.write(str,0,str.length());
		}
		catch(Exception e)
		{
			System.out.println("Error Occurred : "+e.getMessage());
		}
		finally
		{
			// SHOULD CLOSE STREAMS FINALLY
			try
			{
				if(bw!=null)
					bw.close();
				if(osw!=null)
					osw.close();
			}
			catch(Exception ex)
			{
				System.out.println("Error Occurred : "+ex.getMessage());
			}
		}
	}
}

The above program output may look a little different from what you expected because System.in is line buffered, by default. This means that no input is actually passed to the program until you press ENTER. As you can guess, this does not make read() particularly valuable for interactive console input.

How to write String to console

The following program demonstrates BufferedReader and the readLine() method; the program reads and displays lines of text until you enter the word "stop".

/*	How to write String to console Example
	Save with file name BufferedWriterExample2.java	*/
import java.io.*;
public class BufferedWriterExample2
{
	public static void main(String args[])
	{
		// java.io.BufferedWriter DECLARATION
		java.io.BufferedWriter bw = null;
		// OutputStreamWriter DECLARATION
		OutputStreamWriter osw = null;
		// WE SHOULD USE try-catch BECAUSE MOST OF THE
		// JAVA I/O CLASES THROWS IOException
		try
		{
			String str = "This is test String 1 for BufferedWriter.";
			String str2 = "This is test String 2 for newline method in BufferedWriter.";
			osw = new OutputStreamWriter(System.out);
			bw = new BufferedWriter(osw);
			bw.write(str,0,str.length());
			// WRITES NEW LINE CHARACTER TO OUTPUT STREAM
			bw.newLine();
			bw.write(str2,0,str2.length());
	 
		}
		catch(Exception e)
		{
			System.out.println("Error Occurred : "+e.getMessage());
		}
		finally
		{
			// SHOULD CLOSE STREAMS FINALLY
			try
			{
				if(bw!=null)
					bw.close();
				if(osw!=null)
					osw.close();
			}
			catch(Exception ex)
			{
				System.out.println("Error Occurred : "+ex.getMessage());
			}
		}
	}
}

How to read the text from file write to console

How to print only directory names using java? How to get only directories from given path using java?

/*	How to read the text from file write to console Example
	Save with file name BufferedWriterExample3.java	*/
import java.io.*;
public class BufferedWriterExample3
{
	public static void main(String args[])
	{
		// java.io.BufferedWriter DECLARATION
		java.io.BufferedWriter bw = null;
		// OutputStreamWriter DECLARATION
		OutputStreamWriter osw = null;
		// java.io.BufferedReader DECLARATION
		java.io.BufferedReader br = null;
		// InputStreamReader DECLARATION
		InputStreamReader ir = null;
		// FileInputStream DECLARATION
		FileInputStream fis = null;
		// WE SHOULD USE try-catch BECAUSE MOST OF THE
		// JAVA I/O CLASES THROWS IOException
		try
		{
			int ch;
			osw = new OutputStreamWriter(System.out);
			bw = new BufferedWriter(osw);
			fis = new FileInputStream("BufferedWriterExample3.java");
			ir = new InputStreamReader(fis);
			br = new BufferedReader(ir);
			while((ch = br.read()) != -1)
			{
				bw.write(ch);
			}
		}
		catch(Exception e)
		{
			System.out.println("Error Occurred : "+e.getMessage());
		}
		finally
		{
			// SHOULD CLOSE STREAMS FINALLY
			try
			{
				if(bw!=null)
					bw.close();
				if(osw!=null)
					osw.close();
				if(br!=null)
					br.close();
				if(ir!=null)
					ir.close();
				if(fis!=null)
					fis.close();
			}
			catch(Exception ex)
			{
				System.out.println("Error Occurred : "+ex.getMessage());
			}
		}
	}
}

How to read total bytes from file into array and write to console

How to print available file system root names using java? How to get file system roots using java? How to get available drives using java?

/*	How to read total bytes from file into array
	and write to console Example
	Save with file name BufferedWriterExample4.java	*/
import java.io.*;
public class BufferedWriterExample4
{
	public static void main(String args[])
	{
		// java.io.BufferedWriter DECLARATION
		java.io.BufferedWriter bw = null;
		// OutputStreamWriter DECLARATION
		OutputStreamWriter osw = null;
		// java.io.BufferedReader DECLARATION
		java.io.BufferedReader br = null;
		// InputStreamReader DECLARATION
		InputStreamReader ir = null;
		// FileInputStream DECLARATION
		FileInputStream fis = null;
		// ARRAY TO READ BYTES
		char charbuff[] = null;
		// WE SHOULD USE try-catch BECAUSE MOST OF THE
		// JAVA I/O CLASES THROWS IOException
		try
		{
			int ch;
			osw = new OutputStreamWriter(System.out);
			bw = new BufferedWriter(osw);
			fis = new FileInputStream("BufferedWriterExample4.java");
			ir = new InputStreamReader(fis);
			br = new BufferedReader(ir);
			// GET THE AVAILABLE BYTES FROM InputReader AND CREATES ARRAY
			charbuff = new char[fis.available()];
			// READ TOTAL BYTES FROM FILE
			br.read(charbuff, 0,fis.available());
			bw.write(charbuff, 0,charbuff.length);
		}
		catch(Exception e)
		{
			System.out.println("Error Occurred : "+e.getMessage());
		}
		finally
		{
			// SHOULD CLOSE STREAMS FINALLY
			try
			{
				// RELEASE ARRAY MEMORY
				charbuff = null;
				if(bw!=null)
					bw.close();
				if(osw!=null)
					osw.close();
				if(br!=null)
					br.close();
				if(ir!=null)
					ir.close();
				if(fis!=null)
					fis.close();
			}
			catch(Exception ex)
			{
				System.out.println("Error Occurred : "+ex.getMessage());
			}
		}
	}
}