- Write values to file java
- Writing individual bytes with FileOutputStream
- Writing byte arrays with FileOutputStream
- Writing binary data with the NIO.2 OutputStream
- Write faster with BufferedOutputStream
- Writing byte arrays with BufferedOutputStream
- Writing text files with FileWriter
- Write text files faster with BufferedWriter
- Write text files faster with the NIO.2 BufferedWriter
- Performance overview: writing files
- Overview FileOutputStream, FileWriter, OutputStreamWriter, BufferedOutputStream, BufferedWriter
- Character encoding
- What character encoding does Java use by default to write text files?
- How to specify the character encoding when writing a text file?
- Summary and outlook
- Java Write to File — 4 Ways to Write File in Java
- Java Write to File
- Java Write to File Example
Write values to file java
To progressively write data to a file, use a FileOutputStream (or related classes). These were available before Java 7 and made writing small files unnecessarily complicated. In the following sections, I present various options.
Writing individual bytes with FileOutputStream
The primary class is FileOutputStream . It writes data byte by byte into a file. The following example shows how bytes returned by the process() method are successively written to a file (until the method returns -1):
String fileName = . ; try (FileOutputStream out = new FileOutputStream(fileName)) < int b; while ((b = process()) != -1) < out.write(b); > >
Code language: GLSL (glsl)
Writing individual bytes is an expensive operation. Writing 100,000,000 bytes to a test file takes about 230 seconds on my system; that’s just a little more than 0.4 MB per second.
Writing byte arrays with FileOutputStream
Using FileOutputStream , you can also write byte arrays. In the following example, the process() method returns byte arrays instead of individual bytes (and null if no more data is available):
String fileName = . ; try (FileOutputStream out = new FileOutputStream(fileName)) < byte[] bytes; while ((bytes = process()) != null) < out.write(bytes); >>
Code language: GML (gml)
This method is several times faster. If you write 10 bytes 10,000,000 times (the same amount in total), you only need 24 seconds, a little more than a tenth of the previous time. If you write 100 bytes 1,000,000 times, it’s only 2.6 seconds, which is a little more than a hundredth of the previous time. What is relevant here is primarily the number of write operations, not the actual amount of data. This is because the data is written block-wise to the storage medium. Naturally, this only applies up to a specific buffer size. Writing ten gigabytes at a time is no faster than writing ten times one gigabyte. The optimal value for the buffer size depends on the hardware as well as the formatting of the medium. Using a small test program, I measured the write speed in relation to the buffer size:
On my system, the optimal buffer size is 8 KB. At this size, the write speed reaches 1,050 MB per second. 8 KB is also the optimal size on most other systems, which is why Java uses this value as default, as you can see in a later section.
Writing binary data with the NIO.2 OutputStream
String fileName = . ; try (OutputStream out = Files.newOutputStream(Path.of(fileName))) < int b; while ((b = process()) != -1) < out.write(b); >>
Code language: Java (java)
This method returns a ChannelOutputStream instead of a FileOutputStream . On my system, there is no relevant speed difference compared to new FileOutputStream() when writing individual bytes or byte blocks.
Write faster with BufferedOutputStream
We have previously observed that writing blocks is much faster than writing individual bytes. BufferedOutputStream takes advantage of this fact by first buffering the bytes to be written in a buffer and then writing them to disk when the buffer is full. By default, this buffer is 8 KB in size, which is precisely the size that leads to optimal write speed.
String fileName = . ; try (FileOutputStream out = new FileOutputStream(fileName); BufferedOutputStream bout = new BufferedOutputStream(out)) < int b; while ((b = process()) != -1) < bout.write(b); >>
Code language: GLSL (glsl)
Using BufferedOutputStream , my system needs about 250 ms to write 100,000,000 individual bytes. That’s about 400 MB per second. The reason we’re not reaching the 1,050 MB/s from the previous test is the overhead of the buffering logic.
Writing byte arrays with BufferedOutputStream
Just like FileOutputStream , BufferedOutputStream can write not only individual bytes but also byte blocks:
String fileName = . ; try (FileOutputStream out = new FileOutputStream(fileName); BufferedOutputStream bout = new BufferedOutputStream(out)) < byte[] bytes; while ((bytes = process()) != null) < bout.write(bytes); >>
Code language: Java (java)
This method combines the advantages of writing byte arrays with those of a buffer. It almost always delivers optimum write speeds. For writing binary data, I always recommend using this method.
Writing text files with FileWriter
For writing text to a file, it must be converted to binary data. Character-to-byte conversion is the OutputStreamWriter ‘s responsibility. You wrap it around the FileOutputStream as follows. The process() method in the following example produces individual characters.
String fileName = . ; try (FileOutputStream out = new FileOutputStream(fileName); OutputStreamWriter writer = new OutputStreamWriter(out)) < int c; while ((c = process()) != -1) < writer.write(c); >>
Code language: Java (java)
FileWriter is more convenient. It combines FileOutputStream and OutputStreamWriter . The following code is equivalent to the previous one:
String fileName = . ; try (FileWriter writer = new FileWriter(fileName)) < int c; while ((c = process()) != -1) < writer.write(c); >>
Code language: Java (java)
OutputStreamWriter also uses an 8 KB buffer internally. Writing 100,000,000 characters to a text file takes about 2.5 seconds.
Write text files faster with BufferedWriter
String fileName = . ; try (FileWriter writer = new FileWriter(fileName); BufferedWriter bufferedWriter = new BufferedWriter(writer)) < int c; while ((c = process()) != -1) < bufferedWriter.write(c); >>
Code language: Java (java)
BufferedWriter adds another 8 KB buffer for characters, which are then encoded in one go when the buffer is written (instead of character by character). This second buffer reduces the writing time for 100,000,000 characters to approximately 370 ms.
Write text files faster with the NIO.2 BufferedWriter
String fileName = . ; try (BufferedWriter bufferedWriter = Files.newBufferedWriter(Path.of(fileName))) < int c; while ((c = process()) != -1) < bufferedWriter.write(c); >>
Code language: Java (java)
The write speed on my system is about the same as the speed of the «classically» created BufferedWriter .
Performance overview: writing files
In the following diagram, you can see how much time the methods presented need to write 100,000,000 bytes or characters into a binary or text file:
Due to the large gap between unbuffered and buffered writing, the buffered methods hardly stand out here. The following diagram, therefore, only shows the methods that use a buffer:
Overview FileOutputStream, FileWriter, OutputStreamWriter, BufferedOutputStream, BufferedWriter
The following diagram shows the context of the java.io classes presented in this article for writing binary and text files:
Solid lines represent binary data; dashed lines represent text data. FileWriter combines FileOutputStream and OutputStreamWriter .
Character encoding
The subject of character encoding and the problems that go with it have been discussed in detail in the previous article. Therefore, I’ve limited the following sections to those aspects that are relevant for writing text files with Java.
What character encoding does Java use by default to write text files?
- The FileWriter and OutputStreamWriter classes internally use StreamEncoder.forOutputStreamWriter() . If you call this method without a specific character encoding, it uses Charset.defaultCharset() . This method, in turn, reads the character encoding from the system property «file.encoding». If the system property is not specified, it uses ISO-8859-1 by default up to Java 5 and UTF-8 since Java 6.
- The Files.writeString() , Files.write() and Files.newBufferedWriter() methods all use UTF-8 as default encoding without reading the system property mentioned above.
Due to these inconsistencies, you should always specify the character encoding. I always recommend using UTF-8. According to Wikipedia, UTF-8 encoding is used on 94.4% of all websites and can, therefore, be regarded as a de-facto standard. An exception is, of course, when you have to work with old files written in a different encoding.
How to specify the character encoding when writing a text file?
In the following you will find an example for all methods discussed so far with the character encoding set to UTF-8:
- Files.writeString(path, string, StandardCharsets.UTF_8)
- Files.write(path, lines, StandardCharsets.UTF_8)
- new FileWriter(file, StandardCharsets.UTF_8) // this method only exists since Java 11
- new InputStreamWriter(outputStream, StandardCharsets.UTF_8)
- Files.newBufferedWriter(path, StandardCharsets.UTF_8)
Summary and outlook
This article has shown different methods for writing byte arrays and Strings in binary and text files in Java.
In future articles of this series, I will show:
In the further course of the series, more advanced topics will be covered:
- The NIO channels and buffers introduced in Java 1.4 to speed up working with large files in particular .
- Memory-mapped I/O for ultra-fast file access without streams.
- File locking to access the same files from multiple threads or processes in parallel without conflict.
Would you like to be informed when future articles are published? Then click here to sign up for the HappyCoders newsletter. If you liked the article, I’m also happy if you share it via one of the buttons at the end.
Java Write to File — 4 Ways to Write File in Java
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Java provides several ways to write to file. We can use FileWriter, BufferedWriter, java 7 Files and FileOutputStream to write a file in Java.
Java Write to File
Let’s have a brief look at four options we have for java write to file operation.
- FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
- BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more.
- FileOutputStream: FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.
- Files: Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file.
Java Write to File Example
Here is the example showing how we can write a file in java using FileWriter, BufferedWriter, FileOutputStream, and Files in java. WriteFile.java
package com.journaldev.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFile < /** * This class shows how to write file in java * @param args * @throws IOException */ public static void main(String[] args) < String data = "I will write this String to File in Java"; int noOfLines = 10000; writeUsingFileWriter(data); writeUsingBufferedWriter(data, noOfLines); writeUsingFiles(data); writeUsingOutputStream(data); System.out.println("DONE"); >/** * Use Streams when you are dealing with raw data * @param data */ private static void writeUsingOutputStream(String data) < OutputStream os = null; try < os = new FileOutputStream(new File("/Users/pankaj/os.txt")); os.write(data.getBytes(), 0, data.length()); >catch (IOException e) < e.printStackTrace(); >finally < try < os.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use Files class from Java 1.7 to write files, internally uses OutputStream * @param data */ private static void writeUsingFiles(String data) < try < Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes()); >catch (IOException e) < e.printStackTrace(); >> /** * Use BufferedWriter when number of write operations are more * It uses internal buffer to reduce real IO operations and saves time * @param data * @param noOfLines */ private static void writeUsingBufferedWriter(String data, int noOfLines) < File file = new File("/Users/pankaj/BufferedWriter.txt"); FileWriter fr = null; BufferedWriter br = null; String dataWithNewLine=data+System.getProperty("line.separator"); try< fr = new FileWriter(file); br = new BufferedWriter(fr); for(int i = noOfLines; i>0; i--) < br.write(dataWithNewLine); >> catch (IOException e) < e.printStackTrace(); >finally < try < br.close(); fr.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use FileWriter when number of write operations are less * @param data */ private static void writeUsingFileWriter(String data) < File file = new File("/Users/pankaj/FileWriter.txt"); FileWriter fr = null; try < fr = new FileWriter(file); fr.write(data); >catch (IOException e) < e.printStackTrace(); >finally < //close resources try < fr.close(); >catch (IOException e) < e.printStackTrace(); >> > >
These are the standard methods to write a file in java and you should choose any one of these based on your project requirements. That’s all for Java write to file example.
You can checkout more Java IO examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.