Writing to files is crucial for many Java applications, whether it’s saving data, logging, or storing configurations.
Writing Text to a File Using FileWriter and BufferedWriter
- FileWriter: The
FileWriterclass is used to write character data to a file. It writes directly to the file, one character at a time.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.FileWriter; import java.io.IOException; public class FileWriterExample { public static void main(String[] args) { try (FileWriter writer = new FileWriter("output.txt")) { writer.write("Hello, world!"); } catch (IOException e) { e.printStackTrace(); } } } |
- BufferedWriter: For more efficient writing, we can use
BufferedWriter. It is often used in conjunction withFileWriterto buffer the output. This reduces the number of write operations, making the program run more efficiently, especially when writing large amounts of data.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) { writer.write("Hello, world!"); writer.newLine(); // Write a newline character writer.write("This is a new line!"); } catch (IOException e) { e.printStackTrace(); } } } |
Writing Binary Data to a File Using FileOutputStream
When dealing with binary data, such as images or audio files, FileOutputStream is the appropriate choice. This class is used for writing raw byte data to a file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.FileOutputStream; import java.io.IOException; public class FileOutputStreamExample { public static void main(String[] args) { try (FileOutputStream outputStream = new FileOutputStream("output.dat")) { byte[] data = {65, 66, 67}; // ASCII values for 'A', 'B', 'C' outputStream.write(data); } catch (IOException e) { e.printStackTrace(); } } } |
Appending Data to Files
By default, file writing operations overwrite the existing content of a file. However, we can append new data to the end of the file instead of replacing the existing content. To do this, use the FileWriter constructor that accepts a boolean value true to enable append mode.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.FileWriter; import java.io.IOException; public class AppendToFileExample { public static void main(String[] args) { try (FileWriter writer = new FileWriter("output.txt", true)) { writer.write("This is appended text!\n"); } catch (IOException e) { e.printStackTrace(); } } } |
Using Files.write() (NIO) for File Writing
Java’s NIO (New I/O) package provides a more modern and flexible way to handle file operations. Files.write() is a convenient method from the java.nio.file.Files class that allows us to write data to a file in a more streamlined way.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.nio.file.*; import java.io.IOException; public class FilesWriteExample { public static void main(String[] args) { Path path = Paths.get("output.txt"); String content = "This is a line written using NIO!"; try { Files.write(path, content.getBytes()); } catch (IOException e) { e.printStackTrace(); } } } |
Writing to Files with Auto-Flush
When writing to a file, it’s important to ensure that the data is actually saved to the file rather than being kept in memory. One way to ensure this is to use auto-flushing. The PrintWriter class in Java has an option for auto-flushing, which ensures that data is written immediately after each call to println() or write().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.PrintWriter; import java.io.FileNotFoundException; public class AutoFlushExample { public static void main(String[] args) { try (PrintWriter writer = new PrintWriter("output.txt", "UTF-8")) { writer.println("This line is automatically flushed!"); writer.flush(); // Explicit flush, but auto-flush is enabled. } catch (FileNotFoundException e) { e.printStackTrace(); } } } |