Sử dụng FileInputStream để đọc file trong Java

Đọc file cơ bản sử dụng java FileInputStream

Nội dung file text :

Line 1
Line 2
Line 3
Line 4
Line 5

Tạo class ReadTextFile.java

package com.loop.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadTextFile {
  public static void main(String[] args) {
    File file = new File("resource/textFile.txt");
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(file);
      System.out.println("Tổng số bytes : " + fis.available());
      int content;
      while ((content = fis.read()) != -1) {
        System.out.print((char) content);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (fis != null)
        fis.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

Kết quả :

Tổng số bytes : 40
Line 1
Line 2
Line 3
Line 4
Line 5

Đọc file sủ dụng try catch resource với JDK7

Nội dung file text :

Line 1
Line 2
Line 3
Line 4
Line 5

Tạo class ReadTextFile.java

package com.loop.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadTextFile {
  public static void main(String[] args) {
    File file = new File("resource/textFile.txt");
    try (FileInputStream fis = new FileInputStream(file)) {
      System.out.println("Tổng số bytes : " + fis.available());
      int content;
      while ((content = fis.read()) != -1) {
        System.out.print((char) content);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Kết quả :

Tổng số bytes : 40
Line 1
Line 2
Line 3
Line 4
Line 5

Rate this post
Click Here to Leave a Comment Below 0 comments