Bài hướng dẫn này, chúng ta sẽ tìm hiểu làm thế nào để đọc file trong Java. 2 cách dễ dàng sẽ được sử dụng:
Loạt bài hướng dẫn về JAVA IO :
1- BufferedReader
Cách dễ dàng đầu tiên để đọc file là sử dụng BufferedReader lớp từ java.io gói. Dưới đây là một ví dụ:
public class BufferedReaderTutorial {
public static void main(String[] args) {
//Make sure you use \\ instead of \
String filePath = "C:\\files\\file.txt";
Reader reader;
BufferedReader bufferedReader = null;
try {
//Opening the file
reader = new FileReader(filePath);
bufferedReader = new BufferedReader(reader);
//Reading the file
String currentLine;
while ((currentLine = bufferedReader.readLine()) != null) {
System.out.println(currentLine);
}
} catch (FileNotFoundException e) {
System.out.println("The file " + filePath + "is not found !");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Problem occurs when reading file !");
e.printStackTrace();
} finally {
//Closing the file
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println("Problem occurs when closing file !");
e.printStackTrace();
}
}
}
}
}
2- Scanner
Cách thứ hai là sử dụng Scanner từ gói java.util.
public static void main(String[] args) {
// Make sure you use \\ instead of \
String filePath = "C:\\files\\file.txt";
Scanner scanner = null;
File file = new File(filePath);
try {
//Opening the file
scanner = new Scanner(file);
//Reading the file
while(scanner.hasNext()) {
String currentLine = scanner.nextLine();
System.out.println(currentLine);
}
} catch (FileNotFoundException e) {
System.out.println("The file " + filePath + "is not found !");
e.printStackTrace();
} finally {
//Closing the file
scanner.close();
}
}

