BufferedWriter Class

Advantage
When you want to write strings there are two options. The BufferedWriter and the File Writer .- If you want to write one string the File Writer is better.
- If you want to write multiple strings, the BufferedWriter is more efficient.
import java.util.*;
import java.io.*;
public class TestClass{
public static void main(String[] args) {
try {
String weekdays[] = {"Monday",
"Tuesday",
"Wednsday",
"Thursday",
"Friday"};
File file = new File("D:/test.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i=0;i<weekdays.length;i++){
bw.write(weekdays[i]);
bw.newLine();
}
bw.flush();
bw.close();
fw.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
If you just want to print out the array like [a, b, c, ....], you can replace the loop with this one liner:
bw.write(Arrays.toString(weekdays));
How to append text to an existing file in Java?
The constructor FileWriter(file,true) append new content to the end of a file.
FileWriter fw = new FileWriter(file);
In the above code, all existing content will be overridden.
FileWriter fw = new FileWriter(file,true);
Above code keep the existing content and append the new content to the end of a file.
The following Java program append the new content to the end of a file.
import java.util.*;
import java.io.*;
public class TestClass{
public static void main(String[] args) {
try {
String weekdays[] = {"Saturday",
"Sunday"};
File file = new File("D:/test.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
for(int i=0;i<weekdays.length;i++){
bw.write(weekdays[i]);
bw.newLine();
}
bw.flush();
bw.close();
fw.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
Related Topics