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

前端 未结 21 2803
心在旅途
心在旅途 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:19

    FileReader won't let you specify the encoding, use InputStreamReaderinstead if you need to specify it:

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "Cp1252"));         
    
        String line;
        while ((line = br.readLine()) != null) {
            // process the line.
        }
        br.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    If you imported this file from Windows, it might have ANSI encoding (Cp1252), so you have to specify the encoding.

提交回复
热议问题