How to write String in a file using BufferedWriter?
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
String content = "victory has hundred fathers but defeat is orphan";
fw = new FileWriter("e:/govindbufferedwriterexample.txt");
bw = new BufferedWriter(fw);
bw.write(content);
System.out.println("File created successfully inside e folder and file name is govindbufferedwriterexample.txt and content is victory has hundred fathers but defeat is orphan ");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExampleTryWithResources {
public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("e:/govind.txt"))) {
String content = "My name is khan";
bw.write(content);
// no need to close it.
//bw.close();
System.out.println("File created successfully in side e folder with govind.txt file and content is my name is khan");
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedWriter – Append
append to end of file
FileWriter fw = new FileWriter(FILENAME, true);
BufferedWriter bw = new BufferedWriter(fw);
No comments:
Post a Comment