When we use FileOutputStream or BufferedOutputStream we need to convert String into byte array to write in file
But while using BufferedWriter we need not to convert String into byte array to write in file, String can be written directly in file, because BufferedWriter provides more efficient way of writing characters in file
Program to Write String to file using BufferedWriter and FileWriter in java file IO >
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class WriteToFileUsingBufferedWriter {
public static void main(String... args) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
// if file doesn't exist new file will be created
// if file already exists contends will be overridden.
fw = new FileWriter("c:/myFile.txt");
bw = new BufferedWriter(fw);
String str="You are learning File IO from javaMadeSoEasy.com";
bw.write(str); //write String directly in file, no need to convert in byte array
bw.flush(); //flushes the bufferedWriter
System.out.println("String str has been written successfully in file "
+ "using BufferedWriter");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null){
bw.close(); //close BufferedWriter
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* OUTPUT
String str has been written successfully in file using BufferedWriter
*/
|
Read : Should we close both FileInputStream and BufferedInputStream ? OR BufferedReader and FileReader ?
RELATED LINKS>
Write String to file using FileOutputStream in java file IO
Write String to file using BufferedOutputStream (and FileOutputStream) in java file IO
Program to Write in file using PrintWriter to in java
Important Differences in File handling >
Difference between Stream (FileInputStream) and Reader (FileReader) in java file handling
Labels:
Core Java
File IO/File handling