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

1. Đọc file cơ bản sử dụng java InputStreamReader

Nội dung file textFile.txt

Line 1
Line 2
Line 3
Line 4
Line 5

Tạo class ReadFileWIthInputStreamReader.java

package com.loop.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadFileWIthInputStreamReader {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) throws IOException {
    FileInputStream fin = null;
    InputStreamReader in = null;
    try {
      fin = new FileInputStream("resource/textFile.txt");
      in = new InputStreamReader(fin, "UTF8");
      int contents;
      while ((contents = in.read()) != -1) {
        System.out.print((char) contents);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != fin) {
        fin.close();
      }
      if (null != in) {
        in.close();
      }
    }
  }
}

Kết quả

Line 1
Line 2
Line 3
Line 4
Line 5

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

Nội dung file textFile.txt

Line 1
Line 2
Line 3
Line 4
Line 5

Tạo class ReadFileWIthInputStreamReader.java

package com.loop.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadFileWithInputStreamReaderTryWithResource {
  /**
  *
  * Create by Cuder
  */
  public static void main(String[] args) throws IOException {
    try (InputStreamReader in = new InputStreamReader(new FileInputStream("resource/textFile.txt"), "UTF8");) {
      int contents;
      while ((contents = in.read()) != -1) {
        System.out.print((char) contents);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Kết quả

Line 1
Line 2
Line 3
Line 4
Line 5

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