Java how to write to text file
Java how to write to text file
Java – Write to File
Last modified: August 22, 2020
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this tutorial, we’ll explore different ways to write to a file using Java. We’ll make use of BufferedWriter, PrintWriter, FileOutputStream, DataOutputStream, RandomAccessFile, FileChannel, and the Java 7 Files utility class.
We’ll also look at locking the file while writing and discuss some final takeaways on writing to file.
This tutorial is part of the Java “Back to Basics” series here on Baeldung.
Further reading:
Java – Append Data to a File
FileNotFoundException in Java
How to Copy a File with Java
2. Write With BufferedWriter
Let’s start simple and use BufferedWriter to write a String to a new file:
The output in the file will be:
We can then append a String to the existing file:
The file will then be:
3. Write With PrintWriter
Next, let’s see how we can use PrintWriter to write formatted text to a file:
The resulting file will contain:
Note how we’re not only writing a raw String to a file, but also some formatted text with the printf method.
We can create the writer using FileWriter, BufferedWriter, or even System.out.
4. Write With FileOutputStream
Let’s now see how we can use FileOutputStream to write binary data to a file.
The following code converts a String into bytes and writes the bytes to a file using FileOutputStream:
The output in the file will of course be:
5. Write With DataOutputStream
Next, let’s take a look at how we can use DataOutputStream to write a String to a file:
6. Write With RandomAccessFile
Let’s now illustrate how to write and edit inside an existing file rather than just writing to a completely new file or appending to an existing one. Simply put: We need random access.
RandomAccessFile enables us to write at a specific position in the file given the offset — from the beginning of the file — in bytes.
This code writes an integer value with offset given from the beginning of the file:
If we want to read the int stored at a specific location, we can use this method:
To test our functions, let’s write an integer, edit it, and finally read it back:
7. Write With FileChannel
If we are dealing with large files, FileChannel can be faster than standard IO. The following code writes String to a file using FileChannel:
8. Write With Files Class
Java 7 introduces a new way of working with the filesystem, along with a new utility class: Files.
Using the Files class, we can create, move, copy, and delete files and directories. It can also be used to read and write to a file:
9. Write to a Temporary File
Now let’s try to write to a temporary file. The following code creates a temporary file and writes a String to it:
As we can see, it’s just the creation of the temporary file that is interesting and different. After that point, writing to the file is the same.
10. Lock File Before Writing
Finally, when writing to a file, we sometimes need to make extra sure that no one else is writing to that file at the same time. Basically, we need to be able to lock that file while writing.
Let’s make use of FileChannel to try locking the file before writing to it:
Note that if the file is already locked when we try to acquire the lock, an OverlappingFileLockException will be thrown.
11. Notes
After exploring so many methods of writing to a file, let’s discuss some important notes:
Looking at the common usage practices, we can see, for example, that PrintWriter is used to write formatted text, FileOutputStream to write binary data, DataOutputStream to write primitive data types, RandomAccessFile to write to a specific position, and FileChannel to write faster in larger files. Some of the APIs of these classes do allow more, but this is a good place to start.
12. Conclusion
This article illustrated the many options of writing data to a file using Java.
The implementation of all these examples and code snippets can be found over on GitHub.
How to Read and Write Text File in Java
1. Reader, InputStreamReader, FileReader and BufferedReader
FileReader is a convenient class for reading text files using the default character encoding of the operating system.
The following diagram show relationship of these reader classes in the java.io package:
2. Writer, OutputStreamWriter, FileWriter and BufferedWriter
FileWriter is a convenient class for writing text files using the default character encoding of the operating system.
The following diagram show relationship of these writer classes in the java.io package:
3. Character Encoding and Charset
So if we want to use a specific charset, use an InputStreamReader or OutputStreamWriter instead. For example:
That creates a new reader with the Unicode character encoding UTF-16.
And the following statement constructs a writer with the UTF-8 encoding:
And for a BufferedWriter example:
Now, let’s look at some complete examples.
4. Java Reading from Text File Example
The following example reads a text file with assumption that the encoding is UTF-16:
And the following example uses a BufferedReader to read a text file line by line (this is the most efficient and preferred way):
5. Java Writing to Text File Example
Note that, a writer uses default character encoding of the operating system by default. It also creates a new file if not exits, or overwrites the existing one. If you want to append text to an existing file, pass a boolean flag of true to constructor of the writer class:
The following example uses a BufferedReader that wraps a FileReader to append text to an existing file:
This is the preferred way to write to text file because the BufferedReader provides efficient way for writing character streams.
And the following example specifies specific character encoding (UTF-16) when writing to the file:
This program writes some Unicode string (Vietnamese) to the specified text file.
NOTE: From Java 7, you can use try-with-resources statement to simplify the code of opening and closing the reader/writer. For example:
References:
Related File IO Tutorials:
Other Java File IO Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
What is the simplest way to write a text file in Java?
I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner 😀
I searched the web and found this code, but I understand 50% of it.
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
With Java 7 and up, a one liner using Files:
You can use FileUtils from Apache Commons:
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
Files.write() the simple solution as @Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. 🙂
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
How to Write text file Java
The following code does not produce a file (I can’t see the file anywhere). What is missing?
8 Answers 8
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I think your expectations and reality don’t match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
I would like to add a bit more to MadProgrammer’s Answer.
In case of multiple line writing, when executing the command
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
Thus, the whole text comes as one big chunk of text which is undesirable in most cases. The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
and then using the newline variable instead of «\n». This will get the output in the way you want it.
How to Read and Write Text File in Java
1. Reader, InputStreamReader, FileReader and BufferedReader
FileReader is a convenient class for reading text files using the default character encoding of the operating system.
The following diagram show relationship of these reader classes in the java.io package:
2. Writer, OutputStreamWriter, FileWriter and BufferedWriter
FileWriter is a convenient class for writing text files using the default character encoding of the operating system.
The following diagram show relationship of these writer classes in the java.io package:
3. Character Encoding and Charset
So if we want to use a specific charset, use an InputStreamReader or OutputStreamWriter instead. For example:
That creates a new reader with the Unicode character encoding UTF-16.
And the following statement constructs a writer with the UTF-8 encoding:
And for a BufferedWriter example:
Now, let’s look at some complete examples.
4. Java Reading from Text File Example
The following example reads a text file with assumption that the encoding is UTF-16:
And the following example uses a BufferedReader to read a text file line by line (this is the most efficient and preferred way):
5. Java Writing to Text File Example
Note that, a writer uses default character encoding of the operating system by default. It also creates a new file if not exits, or overwrites the existing one. If you want to append text to an existing file, pass a boolean flag of true to constructor of the writer class:
The following example uses a BufferedReader that wraps a FileReader to append text to an existing file:
This is the preferred way to write to text file because the BufferedReader provides efficient way for writing character streams.
And the following example specifies specific character encoding (UTF-16) when writing to the file:
This program writes some Unicode string (Vietnamese) to the specified text file.
NOTE: From Java 7, you can use try-with-resources statement to simplify the code of opening and closing the reader/writer. For example:
References:
Related File IO Tutorials:
Other Java File IO Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Источники информации:
- http://www.codejava.net/java-se/file-io/how-to-read-and-write-text-file-in-java
- http://stackoverflow.com/questions/22859453/what-is-the-simplest-way-to-write-a-text-file-in-java
- http://stackoverflow.com/questions/15754523/how-to-write-text-file-java
- http://mail.codejava.net/java-se/file-io/how-to-read-and-write-text-file-in-java