Menguasai Java FileReader: Panduan Komprehensif dan Contoh Praktis
Java FileReader Class
Panduan ini memandu Anda melalui FileReader Java, mencakup konstruktornya, metode utama, dan contoh praktis.
Kelas FileReader dalam paket java.io membaca data karakter dari file. Ia memperluas InputStreamReader dan mendukung berbagai pengkodean karakter.
Sebelum memulai FileReader, pastikan Anda memahami File API Java.
Membuat FileReader
Pertama, impor kelas:
import java.io.FileReader;
1. By file name
FileReader input = new FileReader("path/to/file.txt");
Membuat reader yang membuka file yang ditentukan.
2. By File object
File fileObj = new File("path/to/file.txt"); FileReader input = new FileReader(fileObj);
3. Specifying a charset (Java 11+)
FileReader input = new FileReader("path/to/file.txt", StandardCharsets.UTF_8);
Menggunakan Charset memungkinkan Anda membaca file dengan pengkodean yang diinginkan.
Key Methods of FileReader
FileReader implements all methods from Reader and adds its own functionality.
read() Method
read() – reads a single character. read(char[] array) – fills the array with characters. read(char[] array, int offset, int length) – reads length characters into the array starting at offset.
Example: Reading input.txt containing “This is a line of text inside the file.”
import java.io.FileReader; class Main { public static void main(String[] args) { char[] buffer = new char[100]; try (FileReader reader = new FileReader("input.txt")) { int readCount = reader.read(buffer); System.out.println("Data in the file:"); System.out.println(new String(buffer, 0, readCount)); } catch (Exception e) { e.printStackTrace(); } } }
Output
Data in the file: This is a line of text inside the file.
Note: Place input.txt in the current working directory.
getEncoding() Method
Retrieve the charset used by the reader:
import java.io.FileReader; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { try { FileReader defaultReader = new FileReader("input.txt"); FileReader utf8Reader = new FileReader("input.txt", StandardCharsets.UTF_8); System.out.println("Default encoding: " + defaultReader.getEncoding()); System.out.println("UTF-8 encoding: " + utf8Reader.getEncoding()); } catch (Exception e) { e.printStackTrace(); } } }
Output
Default encoding: Cp1252 UTF-8 encoding: UTF-8
When a charset is specified, getEncoding() returns that charset; otherwise it reflects the platform default.
close() Method
Always close the reader after use. The try-with-resources statement shown above handles this automatically.
Additional FileReader Methods
| Method | Description |
ready() | Indicates whether the stream is ready to be read. |
mark() | Marks the current position in the stream. |
reset() | Resets the stream to the most recent mark. |
For more details, refer to the official Java FileReader documentation.