0

I need to read the content of a large file. For that I Googled on it and found so many methods and resources. But I'm still confused which is the method to read the large files (Factors need to be consider in my case are memory allocation, performance, large file )

  1. Using FileChannel
  2. using Files.readAllLines
  3. using BufferedReader

Can anyone guide on this?

9
  • And what do you do with the contents? Also, since you mention .readAllLines(), I take it the contents are text?
    – fge
    Nov 13, 2015 at 9:58
  • @DavidG I actually did not add add these lines. There's something wrong here ... I removed the caps from the title and modified the list (also changed so "i" to "I" but that's all
    – LBes
    Nov 13, 2015 at 10:00
  • 1
    @DavidG He didn't add that. He just didn't refresh his edit after someone else made an edit before him. I don't know if he just ignored the message about that fact during his edit.
    – Tom
    Nov 13, 2015 at 10:01
  • @DavidG I know I just checked but I did not add these lines, I'm sure of it. Tom, yup I guess that's the issue. Sorry
    – LBes
    Nov 13, 2015 at 10:02
  • @LBesancon Yes, I see another user trying to add it again, sorry for accusing you! :)
    – DavidG
    Nov 13, 2015 at 10:02

1 Answer 1

2

Your best option is to read the file lazily. Fetch each line one at a time and process.

Example:-

Stream<String> lines = Files.lines(Paths.get("C:/files", "yourfile.txt"));

Then process the lines afterwords.

From the official documentation:-

public static Stream<String> lines(Path path, Charset cs) throws IOException

Read all lines from a file as a Stream. Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed.

3
  • Is this good for performance vice? May I use this in any case
    – yk2
    Nov 13, 2015 at 10:27
  • @KALYANIYOGESWARANATHAN Yes, since the processing happens one line at a time (lazily) it wont be an issue with performance
    – Switch
    Nov 13, 2015 at 10:28
  • @KALYANIYOGESWARANATHAN Please accept the answer if you find what you are looking for.
    – Switch
    Nov 18, 2015 at 9:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.