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

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

    BufferedReader br;
    FileInputStream fin;
    try {
        fin = new FileInputStream(fileName);
        br = new BufferedReader(new InputStreamReader(fin));
    
        /*Path pathToFile = Paths.get(fileName);
        br = Files.newBufferedReader(pathToFile,StandardCharsets.US_ASCII);*/
    
        String line = br.readLine();
        while (line != null) {
            String[] attributes = line.split(",");
            Movie movie = createMovie(attributes);
            movies.add(movie);
            line = br.readLine();
        }
        fin.close();
        br.close();
    } catch (FileNotFoundException e) {
        System.out.println("Your Message");
    } catch (IOException e) {
        System.out.println("Your Message");
    }
    

    It works for me. Hope It will help you too.

提交回复
热议问题