Write to a file in Java
This post will discuss how to write data to a text file in Java. The solution creates the file if it doesn’t exist or truncates the file before writing if it already exists.
There are several methods and classes that we can use to write to a file in Java. Here are some of them:
1. Using Files class
With Java 7, we can use the Files class from NIO package, which provides various utility methods for performing operations on files and directories. It provides methods such as readAllLines(), readAllBytes(), newBufferedWriter(), and write() that may be used to read contents of a file and write text to the file efficiently.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class Main { public static void main(String[] args) { Path path = Paths.get("foo.out"); String text = "sample text"; try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { bw.write(text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
With Java 11, we can also use the Files.writeString() method to write a string to a file using the specified character set and options. It returns the path of the file and will throw an IOException if an I/O error occurs while writing to the file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class Main { public static void main(String[] args) { Path path = Paths.get("foo.out"); String text = "sample text"; try { Files.writeString(path, text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
2. Using FileWriter with BufferedWriter class
FileWriter is a convenience class for writing streams of characters using default character encoding and buffer size. We can create an instance of this class with the file name and use the write() method to write the text to the file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.File; import java.io.FileWriter; import java.io.IOException; class Main { public static void main(String[] args) { File file = new File("foo.out"); String text = "sample text"; try (FileWriter fw = new FileWriter(file)) { fw.write(text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
It is advisable to wrap a BufferedWriter around FileWriter as its write operations are very costly. The BufferedWriter class is used to write buffered characters to a file. It improves the performance of writing by reducing the number of disk operations. We can create an instance of this class with a FileWriter object and use the write() method to write the text to the file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; class Main { public static void main(String[] args) { File file = new File("foo.out"); String text = "sample text"; try (FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw)) { bw.write(text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
3. Using Guava Library
Guava library provides a convenient way to write data to files in Java. It has a static method Files.asCharSink(File, Charset, FileWriteMode) method from the com.google.common.io.Files class, which can be used for writing character data to the given file using the given character set. When no mode is provided, the file will be truncated before writing, or a new file is created when the target file doesn’t exist.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { File file = new File("foo.out"); String text = "sample text"; try { Files.asCharSink(file, StandardCharsets.UTF_8).write(text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
4. Using Apache Commons IO
Apache Commons IO is another good library that can be used to platform write operation on a file. We can use the writeStringToFile(File, String, Charset) method from org.apache.commons.io.FileUtils class to write a string to a file. If the file already exists, then the file will be truncated before writing.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { File file = new File("foo.out"); String text = "sample text"; try { FileUtils.writeStringToFile(file, text, StandardCharsets.UTF_8); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
5. Using PrintWriter with BufferedWriter
We can use the PrintWriter class in situations that require writing characters rather than bytes. However, without buffering, each invocation of PrintWriter’s print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient. Therfore, it is recommended to buffer the output of PrintWriter to the file with BufferedWriter, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.*; class Main { public static void main(String[] args) { File file = new File("foo.out"); String text = "sample text"; try (FileWriter fw = new FileWriter(file); BufferedWriter bf = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bf)) { out.print(text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
6. Using FileOutputStream with OutputStreamWriter
The FileOutputStream class can be used to used to write binary data to a file. We can create an instance of this class with the file name and use the write() method to write the bytes to the file. To write characters instead of bytes, we should use it with an OutputStreamWriter, which can act as a bridge from character streams to byte streams. For top efficiency, it is advisable to wrap a BufferedWriter around OutputStreamWriter whose write operations are costly.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.*; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { File file = new File("foo.out"); String text = "sample text"; try (FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); BufferedWriter bf = new BufferedWriter(osw)) { bf.write(text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
We can also use a PrintStream to add functionality to an output stream. But all characters printed by a PrintStream are converted into bytes using the platform’s default character encoding.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; class Main { public static void main(String[] args) { File file = new File("foo.out"); String text = "sample text"; try (FileOutputStream fos = new FileOutputStream(file); PrintStream out = new PrintStream(fos)) { out.print(text); System.out.println("Successfully written data to the file"); } catch (IOException e) { e.printStackTrace(); } } } |
That’s all about writing to a file in Java.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)