How to Read File in Java: Simple Syntax and Example
To read a file in Java, you can use
BufferedReader with FileReader or the Files.readAllLines() method. These methods let you open a file and read its contents line by line or all at once.Syntax
Here are two common ways to read a file in Java:
- BufferedReader with FileReader: Reads the file line by line.
- Files.readAllLines: Reads all lines into a list at once.
Each method requires specifying the file path.
java
import java.io.BufferedReader; import java.io.FileReader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; try (BufferedReader reader = new BufferedReader(new FileReader("path/to/file.txt"))) { String line; while ((line = reader.readLine()) != null) { // process line } } // Or using Files API List<String> lines = Files.readAllLines(Paths.get("path/to/file.txt"));
Example
This example reads a file named example.txt line by line and prints each line to the console.
java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileExample { public static void main(String[] args) { String filePath = "example.txt"; try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); } } }
Output
Hello, this is line 1.
This is line 2.
End of file.
Common Pitfalls
Common mistakes when reading files in Java include:
- Not closing the file, which can cause resource leaks. Use try-with-resources to close automatically.
- Using incorrect file paths, leading to
FileNotFoundException. - Not handling
IOException, which can crash the program.
java
/* Wrong way: Not closing the reader */ BufferedReader reader = new BufferedReader(new FileReader("file.txt")); String line = reader.readLine(); // reader.close() is missing /* Right way: Using try-with-resources */ try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { String line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); }
Quick Reference
Summary tips for reading files in Java:
- Use
try-with-resourcesto auto-close files. - Choose
BufferedReaderfor line-by-line reading. - Use
Files.readAllLines()for small files to read all lines at once. - Always handle
IOException.
Key Takeaways
Use try-with-resources to automatically close files after reading.
BufferedReader with FileReader reads files line by line efficiently.
Files.readAllLines() reads all lines into a list for small files.
Always handle IOException to avoid program crashes.
Check your file path carefully to prevent FileNotFoundException.