Learn to write the content into a file in Java using BufferedWriter
. Use the given below example as a template and reuse it based on the application requirements.
1. BufferedWriter class
BufferedWriter
is a sub class ofjava.io.Writer
class.BufferedWriter
writes text to character based output stream. It uses buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.BufferedWriter
is used to make lower-level classes likeFileWriter
more efficient and easier to use.BufferedWriter
uses relatively large chunks of data at once, thus minimizing the number of write operations for better performance.
Syntax for creating BufferedWriter
As said earlier, wrap the FileWriter
instance into a BufferedWriter
object.
BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")));
2. BufferedWriter with FileWriter
The FileWriter
class is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream
.
Example: Java Program to write a string to a File using BufferedWriter and FileWriter
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { try { String content = "Hello Learner !! Welcome to howtodoinjava.com."; File file = new File("c:/temp/samplefile.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter x` = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.