首页 > 代码库 > java 读取 txt 文件

java 读取 txt 文件

学习小记:

  1、首先要根据路径获取你的 txt 文本文件。File file = new File(path); 

  2、将获取到的这个字节码流读进缓存。new FileInputStream(file) ;

  3、然后对刚才读进缓存的输入流进行解读,生成对应字节流。InputStreamReader(readIn)

  4、再然后通过 BufferedReader 这个类进行一行一行的输出。bufferedReader.readLine()

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public static void ReadTxt () {
    try {    
        File file = new File("E:\\text.txt");
        FileInputStream readIn = new FileInputStream(file);
        InputStreamReader read = new InputStreamReader(readIn, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(read);
        String oneLine= null;
        while((oneLine= bufferedReader.readLine()) != null){
             System.out.println(lineTxt);
        }
        read.close();
    } catch (Exception e) {
        System.out.println("读取文件内容出错");
        e.printStackTrace();
    }
}

 

java 读取 txt 文件