Reading files is a common task in Java programming, often necessary for data processing and manipulation. Java provides several classes and methods to read files efficiently, with options to handle text and binary data.
Key Classes for File Reading
FileReader: Used for reading text files in a simple and efficient manner.
BufferedReader: Wraps around FileReader to read text from a character-input stream, buffering characters for efficient reading of characters, arrays, and lines.
Files: Part of the java.nio.file package, it provides static methods to read files and directories.
Scanner: A versatile class used for parsing primitive types and strings using regular expressions.
In this example, FileReader and BufferedReader are used to read a text file line by line. The try-with-resources statement ensures that the file is closed after reading.
Example 2: Using Files Class
importjava.io.IOException;importjava.nio.file.Files;importjava.nio.file.Paths;importjava.util.List;publicclassFilesExample{publicstaticvoidmain(String[] args){try{List<String> lines =Files.readAllLines(Paths.get("example.txt"));for(String line : lines){System.out.println(line);}}catch(IOException e){
e.printStackTrace();}}}ขับเคลื่อนโดย
The Files class provides a straightforward way to read all lines of a file into a List<String>. This method is efficient for smaller files.
Reading files is a common task in Java programming, often necessary for data processing and manipulation. Java provides several classes and methods to read files efficiently, with options to handle text and binary data.
Key Classes for File Reading
FileReaderto read text from a character-input stream, buffering characters for efficient reading of characters, arrays, and lines.java.nio.filepackage, it provides static methods to read files and directories.Examples
Example 1: Using FileReader and BufferedReader
In this example,
FileReaderandBufferedReaderare used to read a text file line by line. Thetry-with-resourcesstatement ensures that the file is closed after reading.Example 2: Using Files Class
The
Filesclass provides a straightforward way to read all lines of a file into aList<String>. This method is efficient for smaller files.Example 3: Using Scanner
The
Scannerclass is used here to read a file line by line. It is useful for parsing data with specific delimiters.Tips and Best Practices
try-with-resourcesto ensure that file streams are closed automatically, preventing resource leaks.IOExceptionandFileNotFoundExceptionwhen working with file I/O operations.InputStreamReaderwith a specified charset if necessary.