FileUtils.readFileToByteArray throwing java.lang.OutOfMemoryError: Java heap space error
I am using Apache Commons IO FileUtils utility to read a file into a byte array. The file is 1.13 gigabytes in size. Each time this method is called, I get an out of memory error. I have this running on a Windows Server 2008 64 bit se开发者_运维技巧rver with 8GB of memory. The first time I got this error, I opened up the Tomcat 6 Configuration utility and set the initial memory to 1024 and the Maximum Memory Pool to 2048. I have since tried 3072 and 4096 for the Maximum Memory Pool as well. Each time, I restarted the Tomcat service so that the changes would take. None of these changes fixed this error. Why? I am using Java 1.6 update 14.
attachment.setData(FileUtils.readFileToByteArray(attachmentFile));
The code sample below solved my problem. I'm not exactly sure why though, because I set the buffer length to the length of the file so I don't see how this would be any different than readFileToByteArray. I could see if I set the buffer length to something smaller than the file.
FileInputStream fis = new FileInputStream(attachmentFile);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[(int)attachmentFile.length()];
bis.read(buffer);
fis.close();
精彩评论