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

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

    In Java 7:

    String folderPath = "C:/folderOfMyFile";
    Path path = Paths.get(folderPath, "myFileName.csv"); //or any text file eg.: txt, bat, etc
    Charset charset = Charset.forName("UTF-8");
    
    try (BufferedReader reader = Files.newBufferedReader(path , charset)) {
      while ((line = reader.readLine()) != null ) {
        //separate all csv fields into string array
        String[] lineVariables = line.split(","); 
      }
    } catch (IOException e) {
        System.err.println(e);
    }
    

提交回复
热议问题