How to write to file in Java – BufferedWriter
In Java, we can use BufferedWriter
to write content into a file.
// jdk 7
try (FileWriter writer = new FileWriter("app.log");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
Note
If possible, uses
If possible, uses
Files.write
instead, one line, simple and nice.
List<String> list = Arrays.asList("Line 1", "Line 2");
Files.write(Paths.get("app.log"), list);
Read Files.write examples
1. BufferedWriter
Write content into a file.
FileExample1.java
package com.mkyong;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileExample1 {
public static void main(String[] args) {
String content = "This is the content to write into file\n";
// If the file doesn't exists, create and write to it
// If the file exists, truncate (remove all content) and write to it
try (FileWriter writer = new FileWriter("app.log");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
}
Output
app.log
This is the content to write into file
For Append mode, pass a true
as second argument in FileWriter
// If the file exists, append to it
try (FileWriter writer = new FileWriter("app.log", true);
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
2. BufferedWriter (Old School Style)
Before the JDK 7 try-resources
, we need to handle the close()
manually. A painful memory, let see this :
FileExample2.java
package com.mkyong;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileExample2 {
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
String content = "This is the content to write into file\n";
fw = new FileWriter("app.log");
bw = new BufferedWriter(fw);
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
System.err.format("IOException: %s%n", ex);
}
}
}
}
Output
app.log
This is the content to write into file
Or, much simpler and not wasting any time:
List lines; // The lines in your file
Path file = Paths.get("your-path-here");
Files.write(file, lines);
Article is updated with
Files.write
https://www.mkyong.com/java/java-how-to-create-and-write-to-a-file/
Hi mkyong
Is it possible to answer the below question ?
https://unix.stackexchange.com/questions/511258/word-or-excel-file-is-corrupt-and-cannot-be-opened-where-as-html-is-working-fin
Hi, I want to ask you how can I create a file on another computer for example I m using windows and I try to create a file on linux connected to my network
when Iclose the program and open it again it overwrites all and only place the new entry but i want all data to remain but I can’t find out what is wrong
try {
File file = new File(“driver.txt”);
String drive = “”;
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
for (int i = 0; i < driverList.size(); i++) {
drive = driverList.get(i).getName() + " " + driverList.get(i).getDistance() + " " + driverList.get(i).getCountry() + " " + driverList.get(i).getCity() + " " + driverList.get(i).getTime();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(drive);
bw.close();
System.out.println("Done: " + drive);
} catch (IOException e) {
e.printStackTrace();
}
I have solved the problem
I changed the line saying : FileWriter fw = new FileWriter(file.getAbsoluteFile());
to: FileWriter fw = new FileWriter(file, true);
so now it does not overwrite the old data, but new it just write it in one continuous line to prevent this I added bw.newLine(); just before the write..
thank you very much!
it worked.
thanks sir for nice tutorial but can you tell me why you have used both file writer and bufferwriter.
Thanks a lot for your easy to understand guide.
how to set permission file
Hi mkyong one query i have can we override BufferedWriter write() method into our class?
for which purpose we use file.getAbsoluteFile?
thanxx Mkyong 🙂 its really helpful…
thanks sir mkyong. you help me a lot.
Hi guys, can anyone please help me with this? I’m trying to write 10 lines in a .doc file with a buffered writer. Each line contains a string and a number, as below:
for(int count=0;count<=9;count++){
br.write(accents[count] + ": ");
br.write(results[count] + "%\n");
}
accents is an array of 10 strings, and results is an array of 10 float numbers. How can I change the font color (to red, for example), when results[count] is bigger than a fixed value?
You can’t write directly to a .doc like that
Thnaks!!!
Hi,
thank you for your pieces of code. I am just starting to learn Java – which is kind of whole different bag comapred to Perl and Python I have used previously and your website has some really clear examples.
As I am now getting all giddly with the OO side of everything I thought Id try to do some text file processing that I have done with Perl in Java.
In Perl it has been quite easy to put down read-line->do-stuff(reformat-line)->write-formatted-line.(close)
I see a class here that reads a file line by line and has embedded do stuff-print the line in standard output. I see a class here writes a file.
What I would like to construct myself would be a scheme of three classes.
A to read lines and feed them forward B do stuff on lines and feed them forward C append lines to file. So I dont have to embed the do stuff-and write stuff out parts in the Reading class. (frex. into BufferedReaderExample while loop)
So that I could replace the B class/object any time I want.
Have you any pointers how to set up this system – how should my A and B look like.
When I want seamless line by line editing, and yet don’t want to always embed my editing paert into my reader part.
Do I then have to call my A n-times so it’ll return string n-times, and feed it to the B.
N-being the number of lines in text file. It seems that in such case some internal counter should be needed – also it means the class A should make sure how many lines there are in text file – which would mean an additional read-through. Which would be a waste of time.
Have you encountered such set-up or can show pointers etc. I would like to use the modularity without losing the speed or getting too hackish.
no
Am I in a right direction when I am looking at this example?
http://sfdv3006.wikidot.com/file-sort-filter
wooops not reader its writer lol
hi everyone im actually new hea and im stuck wit bufferedreader codes can anyone help me plss
Thank you 🙂
Mykong
your blog has cleared so many of my confusions……..
will you help me in reading an xml file and printing parent nodes and child nodes
for example
expected output:
employee/name/firstname
employee/name/laststname
employee/age
great help, always result number one when Googling 🙂
Hi Mkyong,
Thank you for all your posts. This is really very helpful as quick reference.
Regards
Anupam
Thank you a lot. Whenever, i get a doubt or need something, i just search it in your website. It’s really helpful.
… can someone please help me with this problem , when the user is inputting the information it isn’t saving in the text file
——————————————————————————————
String name1 = JOptionPane.showInputDialog (“Enter Name & Surname”);
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(“Teldir.txt”));
bufferedWriter.write(“Writing line one to file”);
bufferedWriter.newLine();
bufferedWriter.write(“Writing line two to file”);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
}
try {
Two problems….
1. In the code that Mkyong shows, he never flushes. Before you close the Buffer, you should flush it. Otherwise, the Buffer may never write to disk (because it never fills up). Calling flush() will force the BufferedWriter to empty its contents.
2. Your code never calls close(). After you flush the BufferedWriter, close() it….
-Al
API says close() does a flush first
Hi
whats different between “FileOutputStream” and “BufferedWriter “?
which one do you recommend to use?
thanks a lot
best regards
You use BufferedWriter to write CHARACTERS from a buffer into a file.
FileOutputStream is used to write BYTES into a file directly, not using a buffer.
Hope it helped!
Don’t know why the above code is not working for me. Here a little change in code (given below) did resolve my issue.
You should use “C://filename.txt”. It works for me.
“C:\\filename.txt” is for Windows computers
/users/mkyoung is for Mac
This code will not work. This line “File file =new File(“C:/filename.txt”);” will not work.
Use “\\” instead of “/” in above line where you give the location of file.
C:\\…. is for a windows. This is how the path is typed into a windows.
/users/mkyong/….. is for a mac. This is how the path is typed into a mac.
Hi – Thanks for the sample. Would you happen to know if there is any reason to also close the FileWriter?
Also – Shouldn’t we be closing the streams in a finally clause since if an error occurs in the try we would never get to close()…
finally {
if(br != null) br.close();
if(fw != null) fr.close();
}
Thank you…
Thank you very much. You are like a Java Dictionary for me.
can anyone teach me java
🙁