简体   繁体   English

无法读取Java中文本文件的所有行

[英]Cannot read all lines of text file in java

I'm trying to read a 50000+ lines text file in a Java web application. 我正在尝试在Java Web应用程序中读取50000行以上的文本文件。

I created a Java class to read the text file. 我创建了一个Java类来读取文本文件。 While reading it adds each line to an ArrayList . 在读取时,将每一行添加到ArrayList

After passing that ArrayList to a servlet I can't retrieve all lines from the ArrayList . 在将该ArrayList传递给servlet之后,我无法从ArrayList检索所有行。 Also, I cant get all lines inside of a for loop. 另外,我无法在for循环中获取所有行。 It prints a different amounts of line each time. 每次打印不同数量的行。

public class TextReader {

    public ArrayList<String> readText(InputStream file) {
        ArrayList<String> lst = new ArrayList();
        try {
            InputStreamReader ipsr = new InputStreamReader(file);
            BufferedReader br = new BufferedReader(ipsr, 1024);
            String line;
            while ((line = br.readLine()) != null) {
                lst.add(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lst;
    }
}

in servel i call 我称呼

TextReader tr = new TextReader();
for (String text : tr.readText(new FileInputStream(file))) {
    System.out.println(text);
}

use BufferedReader without InputStreamReader. 使用不带InputStreamReader的BufferedReader。 you can directly pass the file path parameter inside BufferedReader 您可以直接在BufferedReader中传递文件路径参数

    BufferedReader br = new BufferedReader(<file path>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM