Six Ways to Write Files in Java: Streams, Buffers, and Performance Comparison
This article introduces six Java file-writing techniques—including FileWriter, BufferedWriter, PrintWriter, FileOutputStream, BufferedOutputStream, and Files—explains their underlying stream concepts, provides code examples, and benchmarks their performance to guide developers in choosing the most efficient method for text or binary data.
In Java, file operations are fundamentally based on two types of streams: byte streams and character streams, each with numerous implementation classes. This article reviews these methods, provides code examples, and benchmarks their performance to identify the optimal file-writing approach.
0. What is a Stream?
A stream in Java is an abstract concept analogous to water flow, representing data moving from a source to a destination. Streams are categorized by direction into input streams (reading data) and output streams (writing data).
1. What is a Byte Stream?
Byte streams handle binary data with the basic unit of a byte (8 bits). Their two base classes are InputStream (input byte stream) and OutputStream (output byte stream). InputStream is used for read operations, while OutputStream is used for write operations.
2. What is a Character Stream?
Character streams handle text data using Unicode (typically two bytes per character). Their base classes are Reader (input character stream) and Writer (output character stream).
3. Stream Classification
Streams can be classified by direction, data unit, or functionality:
① By Direction
Output streams: OutputStream and Writer Input streams: InputStream and
Reader② By Data Unit
Byte streams: InputStream, OutputStream Character streams: Reader,
Writer③ By Function
Byte streams: read/write data to a specific node.
Processing streams: wrap existing streams to add functionality.
4. Six Ways to Write Files
The following subclasses of Writer and OutputStream can be used for file writing, plus the JDK 7 Files utility.
Method 1: FileWriter
FileWriteris a basic character‑stream class with five constructors; the second parameter controls appending (default false overwrites).
/**
* Method 1: Write file using FileWriter
* @param filepath File path
* @param content Content to write
* @throws IOException
*/
public static void fileWriterMethod(String filepath, String content) throws IOException {
try (FileWriter fileWriter = new FileWriter(filepath)) {
fileWriter.append(content);
}
}Usage example:
public static void main(String[] args) {
fileWriterMethod("/Users/mac/Downloads/io_test/write1.txt", "Hello, Java Chinese Community.");
}Method 2: BufferedWriter
BufferedWriteradds a buffer to FileWriter, improving write performance.
/**
* Method 2: Write file using BufferedWriter
* @param filepath File path
* @param content Content to write
* @throws IOException
*/
public static void bufferedWriterMethod(String filepath, String content) throws IOException {
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filepath))) {
bufferedWriter.write(content);
}
}Method 3: PrintWriter
PrintWriteralso relies on FileWriter and can print text directly.
/**
* Method 3: Write file using PrintWriter
* @param filepath File path
* @param content Content to write
* @throws IOException
*/
public static void printWriterMethod(String filepath, String content) throws IOException {
try (PrintWriter printWriter = new PrintWriter(new FileWriter(filepath))) {
printWriter.print(content);
}
}Method 4: FileOutputStream
Uses a byte stream; the string is first converted to bytes via getBytes().
/**
* Method 4: Write file using FileOutputStream
* @param filepath File path
* @param content Content to write
* @throws IOException
*/
public static void fileOutputStreamMethod(String filepath, String content) throws IOException {
try (FileOutputStream fileOutputStream = new FileOutputStream(filepath)) {
byte[] bytes = content.getBytes();
fileOutputStream.write(bytes);
}
}Method 5: BufferedOutputStream
Wraps FileOutputStream with a buffer for better performance.
/**
* Method 5: Write file using BufferedOutputStream
* @param filepath File path
* @param content Content to write
* @throws IOException
*/
public static void bufferedOutputStreamMethod(String filepath, String content) throws IOException {
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filepath))) {
bufferedOutputStream.write(content.getBytes());
}
}Method 6: Files
The JDK 7 Files class provides a concise way to write bytes to a file.
/**
* Method 6: Write file using Files
* @param filepath File path
* @param content Content to write
* @throws IOException
*/
public static void filesTest(String filepath, String content) throws IOException {
Files.write(Paths.get(filepath), content.getBytes());
}5. Performance Test
A large string (≈26 MB) is written using each of the six methods while measuring elapsed time.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WriteExample {
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
sb.append("ABCDEFGHIGKLMNOPQRSEUVWXYZ");
}
final String content = sb.toString();
final String filepath1 = "/Users/mac/Downloads/io_test/write1.txt";
// ... other file paths omitted for brevity
long stime1 = System.currentTimeMillis();
fileWriterTest(filepath1, content);
long etime1 = System.currentTimeMillis();
System.out.println("FileWriter time:" + (etime1 - stime1));
// Similar timing code for the other five methods
}
// ... method implementations omitted for brevity
}The results show that character‑stream methods, especially BufferedWriter, are the fastest for writing strings, while Files is the slowest. For binary data, a buffered byte stream such as BufferedOutputStream is recommended.
6. Extension: Appending Content
To append rather than overwrite, pass true as the second argument to FileWriter (or to the underlying writer used by BufferedWriter or PrintWriter).
public static void fileWriterMethod(String filepath, String content) throws IOException {
// Append mode
try (FileWriter fileWriter = new FileWriter(filepath, true)) {
fileWriter.append(content);
}
}For Files, use StandardOpenOption.APPEND:
Files.write(Paths.get(filepath), content.getBytes(), StandardOpenOption.APPEND);7. Summary
The article presented six file‑writing approaches, grouped into character streams, byte streams, and the Files utility. While Files offers convenience, buffered streams ( BufferedWriter for text, BufferedOutputStream for binary) deliver superior performance. Choose the method that matches your data type and performance requirements.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
