January 10 2017

Java BufferedWriter Example

Java BufferedWriter Example

BufferedWriter class writes text to a character-output stream, buffering characters and provides efficient writing of single characters, arrays, and strings. Compared to FileWriter, BufferedWriter writes relatively large amount of data to a file at once. The buffer size may be specified, or the default size may be used.

BufferedWriter provides a newLine() method to create platform-specific line separators automatically. Wrap the BufferedWriter around a FileWriter, to get access to high level methods.

Key methods: close(), flush(), newLine(), write()

Example


package com.answersz;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class JavaBufferedwriterExample {

public static void main(String[] args) {

BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;

String fileName = "C:\\answersz\\message.txt";
try {

String content = "answerz.com : java bufferedwriter example program ";

fileWriter = new FileWriter(fileName);
bufferedWriter = new BufferedWriter(fileWriter);

// Write the string
bufferedWriter.write(content);

// Write to new line
bufferedWriter.newLine();

bufferedWriter.append("End of the program");

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (bufferedWriter != null)
bufferedWriter.close();

if (fileWriter != null)
fileWriter.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}
}
}

File- message.txt

answerz.com : java bufferedwriter example program 
End of the program


Copyright © 2014. All rights reserved.

Posted January 10, 2017 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*