如何使用Java的BufferedReader和InputStreamReader读取文件?

时间:2016-03-07 15:17:05

标签: java spring inputstream bufferedreader

下面我有以下代码读取文件并逐行浏览..这是使用java的BufferedReader类。我很好。

String filename = "C:\\test.txt"
String line = null;

FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);

try {
    while (((line = bufferedReader.readLine()) != null)) {

    //do the following....

   }

} catch (IOException) {
    e.printStackTrace();
    }

但是我想现在开始在Spring / Java中使用InputStreamReader。我写了下面的代码,但我不确定如何逐行浏览我的文件。对这一部分真的感到困惑。任何人都有任何想法或知道如何做到这一点?

String filepath= "C:\\test.txt" 
File filename= new File(filepath);

try {
    InputStream fileInputStream = new BOMInputStream(new fileInputStream(filename));

// now want to step through the file, line by line..

} catch (IOException) {
    e.printStackTrace();
    }

由于

3 个答案:

答案 0 :(得分:0)

这是使用InputStreamReader逐字节读取输入文件的方法。

    char[] chars = new char[100];
    try {
        InputStream inputStream       = new FileInputStream("C:\\test.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");           
        inputStreamReader.read(chars);          
        System.out.println(new String(chars).trim());
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

检查出来 -

String filename = "C:\\test.txt"
String line = null;

FileInputStream fileInputStream = new FileInputStream(filename);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

try {
    while (((line = bufferedReader.readLine()) != null)) {

    //do the following....

   }

} catch (IOException) {
    e.printStackTrace();
}

答案 2 :(得分:0)

public static void main(String[] args) {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\test.txt")))) {

        reader.lines().forEach(line -> {
            // do what you want with the line
        });

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}