简体   繁体   中英

Cannot read all lines of text file in java

I'm trying to read a 50000+ lines text file in a Java web application.

I created a Java class to read the text file. While reading it adds each line to an ArrayList .

After passing that ArrayList to a servlet I can't retrieve all lines from the ArrayList . Also, I cant get all lines inside of a for loop. 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. you can directly pass the file path parameter inside BufferedReader

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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