OutOfMemoryError when trying to read/write from a huge text file

前端 未结 4 1084
心在旅途
心在旅途 2021-01-21 04:46

I\'m trying to read/write a huge text file. But when I try to do that I get the error:

Exception in thread \"main\" java.lang.OutOfMemoryError: Java heap space
          


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-21 05:13

    I tried to add a counter (count) so it can flush the buffer after a certain amount of lines read. It didn't work. I know the counter does not work correctly. It doesn't goes to zero After a special number of execution of "while" loop. I added a "for" loop before and after while loop to empty the counter but that didn't work as well.

    Any Suggestion?

    The out of memory error is because your file is so huge that all the contents of that file could not be read into your local variable contents in the function getContents(File aFile).

    Flushing the buffer has nothing to do with it. Using a PrintWriter instead of a BufferedWriter may help clean up the code a bit. By using PrintWriter, you wouldn't have to do something like :

    bw.write(content);
    bw.newLine(); 
    

    You can change this to :

    printWriter.println(content);
    

    You also forgot to tell us your use-case. In the end, all you do is print all the contents of the file. You could have done this line by line.

提交回复
热议问题