Memory issues with InputStream in Java

后端 未结 4 1085
孤城傲影
孤城傲影 2021-01-21 19:31

I need to read a file into an array of Bytes.The entire file needs to be read into the array. The problem is I am getting an OutOfMemory Error since the file size is too large.

4条回答
  •  孤街浪徒
    2021-01-21 19:55

    The workarround would be, not to load the entire file into the RAM. In fact you can't do this for large files, because you have to allocate lots of memory at one peace, which may not work.

    The question ist: Do you really need the entire file in memory?

    edit

    InputStream in = new FileInputStream(file);
    long length = file.length();     
    // At this point a warning should appear, because the code would
    // not work for files larger than Integer.MAX_VALUE                   
    byte[] out = new byte[(int)length]; 
    

提交回复
热议问题