I am looking to convert file input stream for big file (The file is of 100MB) and it is throwing and java.lang.OutOfMemoryError : Java Heap space
import java.io.FileInputStream; import java.io.IOException;
import org.apache.commons.io.IOUtils;
public class TestClass {
public static void main(String args[]) throws IOException
{
//Open the input and out files for the streams
FileInputStream fileInputStream = new FileInputStream("file.pdf");
IOUtils.toByteArray(fileInputStream);
}
}
The actual stack trace is
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at org.apache.commons.io.output.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:322)
at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:463)
at TestClass.main(TestClass.java:12)
I did tried to handle it using the below method
public static byte[] toByteArray(InputStream is) {
if (is == null) {
throw new NullPointerException("The InputStream parameter is null.");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[32];
int read;
while ((read = is.read(buffer)) != -1) {
baos.write(buffer, 0, read);
}
return baos.toByteArray();
} catch (IOException e) {
}
Which then fails with
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2786)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:94)
at TestClass.toByteArray(TestClass.java:25)
at TestClass.main(TestClass.java:14)
Is there any way we could handle this !!! Any inputs will be appreciated.
Thanks !!!