Đọc Nội Dung Một File Trong Java

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. Cách tạo file mới trong Java bằng nhiều cách [Java create file]
  2. Xóa thư mục trong java
  3. Xóa file trong java
  4. Đổi tên file trong java
  5. Ví dụ về xóa một file trong java
  6. Viết nội dung vào file trong java

Table of Contents

Toggle
  • 1- BufferedReader
  • 2- Scanner

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(); } }

Từ khóa » đọc File Trong Java Dụng Scanner