Java BufferedReader Examples
BufferedWriter class present in the java.io package. It implements Closeable, Flushable, Appendable, AutoCloseable.It is present in java since JDK1.1.
BufferedWriter is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
The buffer size may be specified, or the default size.
A newLine() method is used to terminate each output line is therefore preferred to writing a newline character directly.
FileWriter fw = new FileWriter(new File("hello.txt"));
BufferedWriter bw = new BufferedWriter(fw);
Constructor Summary
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 Details
1). public void write(int c) throws IOException
This method is used to write a single character.
2). public void write(char[] cbuf, int off, int len) throws IOException
This method is used to write a portion of an array of characters.
Ordinarily, this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed. If the requested length is at least as large as the buffer, however, then this method will flush the buffer and write the characters directly to the underlying stream. Thus redundant BufferedWriters will not copy data unnecessarily.
Parameters:
cbuf - A character array
off - Offset from which to start reading characters
len - Number of characters to write
3). public void write(String s, int off, int len) throws IOException
This method is used to writes a portion of a String.
If the value of the len parameter is negative then no characters are written.
This is contrary to the specification of this method in the superclass, which requires that an IndexOutOfBoundsException be thrown.
Parameters:
s - String to be written
off - Offset from which to start reading characters
len - Number of characters to be written .
4). public void newLine() throws IOException
This method is used to write a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
5). public void flush() throws IOException
This method is used to flush the stream.
6). public void close() throws IOException
This method is used to Close the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
1). BufferedWriter Example before java7
package com.javacodestuffs.core.io.writer.bufferedwriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterBeforeJava7 {
public static void main(String[] args) {
try {
String contentData = "Java BufferedWriter Tutorial. BufferedWriter Example before java7.";
File file = new File("/home/devuser/hello.txt"); //C:\\devuser\\hello.txt" for Windows
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(contentData);
bw.close();
System.out.println("the content is written to the file.");
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
output: the content is written to the file.
2). BufferedWriter with try-with-resources(Java7 Onwards)
We need not need to close resources like
bw.write(contentData);
bw.close();
try with resources takes care of it for us.
package com.javacodestuffs.core.io.writer.bufferedwriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterJava7Onwards {
public static void main(String[] args) {
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("/home/devuser/hello.txt"))) //C:\\devuser\\hello.txt" for Windows
{
String contentData = "Java BufferedWriter Tutorial. BufferedWriter Example java7 onwards.";
bufferedWriter.write(content);
System.out.println("the content is written to the file.");
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
output: the content is written to the file.
BufferedWriter method examples
1). write(int ch)
package com.javacodestuffs.core.io.writer.bufferedwriter;
import java.io. * ;
public class BufferedWriterWriteExample {
public static void main(String[] args) {
FileWriter fw;
try {
fw = new FileWriter("/home/devuser/hello.txt"); // C:\\devuser\\hello.txt" for Windows
BufferedWriter bw = new BufferedWriter(fw);
bw.write(65); // A
bw.write(49); //1
bw.write(97); //a
bw.close();
System.out.println("content is written to the file.");
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
output:
2). newLine() method
package com.javacodestuffs.core.io.writer.bufferedwriter;
import java.io. * ;
public class BufferedWriterNewLineExample {
public static void main(String[] args) {
FileWriter fw;
try {
fw = new FileWriter("/home/devuser/hello.txt"); // C:\\devuser\\hello.txt" for Windows
BufferedWriter bw = new BufferedWriter(fw);
fw.write("Hello");
fw.newLine();
fw.write("FOR");
fw.newLine();
fw.write("Welcome to Java Programming!!!!");
fw.close();
System.out.println("content is written to the file.");
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
How to read a file and write to another file in java?
package com.javacodestuffs.core.io.writer.bufferedwriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class ReadWriteToFile {
public static void main(String[] args) {
try {
boolean create = true;
Scanner KB = new Scanner(System. in );
System.out.print("Enter Source File Name:");
String sfilename = KB.next();
File srcfile = new File(sfilename);
if (!srcfile.exists()) {
System.out.println("File Not Found..");
}
else {
FileInputStream FI = new FileInputStream(sfilename);
System.out.print("Enter Target File Name:");
String tfilename = KB.next();
File tfile = new File(tfilename);
if (tfile.exists()) {
System.out.print("File Already Exist OverWrite it..Yes/No?:");
String confirm = KB.next();
if (confirm.equalsIgnoreCase("yes")) {
create = true;
}
else {
create = false;
}
}
if (create) {
FileOutputStream FO = new FileOutputStream(tfilename);
int b;
//read content and write in another file
while ((b = FI.read()) != -1) {
FO.write(b);
}
System.out.println("\nFile Copied...");
}
FI.close();
}
}
catch(IOException e) {
System.out.println(e);
}
}
}
Post/Questions related to Java BufferedWriter
How to copy a file from one directory to another in java?
How to put a file into a folder in java?
How to create a directory in java?
How to read all files in a directory in java?
How to delete all files in a directory in java?
How to take input using the buffered writer in java?
How to read the next line using the buffered writer in java?
How to read multiple lines using the buffered writer in java?
What is the use of buffered writer in java?
Do we need to close the Buffered writer in Java?
How to check if directory exists in java?
How to Download File from URL in Java
Read file to byte[] array in Java
Java File Reader Examples
Java file writer Example
java.nio.file.Files methods with Examples
Java File Path, Absolute Path, and Relative Path
Path toString() method in Java
Create New File in Java
In this article, we have seen Java BufferedWriter Tutorial with Examples. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment