Menguasai Java FileWriter: Tutorial Lengkap
Menguasai Java FileWriter: A Complete Tutorial
Temukan cara menggunakan FileWriter Java untuk menulis data karakter ke file, dengan contoh yang jelas, opsi pengkodean, dan metode utama.
Kelas FileWriter dalam paket java.io adalah alat sederhana untuk menulis teks ke file. Ia memperluas OutputStreamWriter dan menggunakan pengkodean karakter default platform kecuali Anda secara eksplisit menetapkan satu.

Sebelum membahas lebih dalam, pastikan Anda memahami dasar-dasar penanganan file Java.
Membuat FileWriter
Untuk membuat instance FileWriter, impor kelas terlebih dahulu:
import java.io.FileWriter;
Ada beberapa cara untuk membuat FileWriter:
- By file name
FileWriter output = new FileWriter("output.txt");
- By
File object File file = new File("output.txt"); FileWriter output = new FileWriter(file);
- With explicit charset (Java 11+)
FileWriter output = new FileWriter("output.txt", StandardCharsets.UTF_8);
Menentukan charset memastikan perilaku yang konsisten di berbagai platform.
Key Methods of FileWriter
write()
write(int c) – writes a single character. write(char[] cbuf) – writes an array of characters. write(String str) – writes a string.
Example: Writing Text to a File
import java.io.FileWriter; public class Main { public static void main(String[] args) { String data = "This is the data in the output file"; try (FileWriter writer = new FileWriter("output.txt")) { writer.write(data); } catch (Exception e) { e.printStackTrace(); } } }
Running this program creates output.txt containing:
This is the data in the output file
getEncoding()
The getEncoding() method reveals the character set used by the writer:
import java.io.FileWriter; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) { try { FileWriter defaultWriter = new FileWriter("output.txt"); FileWriter utf8Writer = new FileWriter("output.txt", StandardCharsets.UTF_8); System.out.println("Default encoding: " + defaultWriter.getEncoding()); System.out.println("UTF‑8 encoding: " + utf8Writer.getEncoding()); defaultWriter.close(); utf8Writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
Output:
Default encoding: Cp1252 UTF‑8 encoding: UTF-8
Use Charset.forName() or StandardCharsets for reliable encoding names.
Tip: Refer to the official Java FileWriter documentation for deeper details.
close()
Always close a FileWriter (or use a try-with-resources block) to flush buffers and release system resources. After closing, the writer cannot be reused.
Other Useful Methods
| Method | Description |
flush() | Immediately writes any buffered data to the underlying stream. |
append() | Conveniently adds characters or strings to the writer. |
For a full list of methods, consult the official Java FileWriter API.