How can I read a large text file line by line using Java?

前端 未结 21 2342
心在旅途
心在旅途 2020-11-21 05:48

I need to read a large text file of around 5-6 GB line by line using Java.

How can I do this quickly?

21条回答
  •  悲&欢浪女
    2020-11-21 06:10

    I usually do the reading routine straightforward:

    void readResource(InputStream source) throws IOException {
        BufferedReader stream = null;
        try {
            stream = new BufferedReader(new InputStreamReader(source));
            while (true) {
                String line = stream.readLine();
                if(line == null) {
                    break;
                }
                //process line
                System.out.println(line)
            }
        } finally {
            closeQuiet(stream);
        }
    }
    
    static void closeQuiet(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException ignore) {
            }
        }
    }
    

提交回复
热议问题