I need to convert a file to a byte array, but I can’t do it with a .mov file (1.32 Gb). The method works fine with small .txt files and JPEG images, but when I try to do it with the MOV file I can’t. I just get a NullPointerException.
code:
public byte[] fileToByteArray(File file){
ByteArrayOutputStream baos = null;
InputStream fis = null;
try{
byte[] buffer = new byte[(int)file.length()];
baos = new ByteArrayOutputStream();
fis = new FileInputStream(file);
int read;
while((read = fis.read(buffer)) != -1){
baos.write(buffer, 0, read);
}
}catch(Exception ex){
System.out.println("Error: 1");
}finally{
try{
if(baos != null){
baos.close();
}
}catch(Exception ex){
System.out.println("Error: 2");
}
try{
if(fis != null){
fis.close();
}
}catch(Exception ex){
System.out.println("Error: 3");
}
return baos.toByteArray();
}
}
In this line:
You’re unconditionally dereferencing
baos… even though it will still be null if this line throws an exception:I suspect that line has thrown an exception (out of memory, at a guess)… but due to your exception handling strategy of “catch all exceptions, print them out and ignore them” you’re keeping going when you shouldn’t.
The immediate fix to this is to only catch the exceptions you really want to catch – which should almost certainly only be
IOExceptionin this case, if anything. In fact, I probably wouldn’t use anycatchclauses in the code you’ve written at all, other than possibly on theclosecode. (You don’t want an exception incloseto obscure an exception elsewhere. If you’re using Java 7, use the try-with-resources statement to make all of this easier to start with.)“Handling” exceptions in the way you’re doing is a very bad idea – you’re basically saying that you want to proceed regardless of what’s gone wrong, and that just makes one error lead to another if you’re lucky, or if you’re unlucky you end up making bad state changes, e.g. overwriting good data with bad, without even realizing it.
Now as for the bigger problem – you’re trying to allocate an enormous array, and I suspect you haven’t told the JVM to use that much memory. You’ll need to start it with something like:
… assuming you’re on a 64-bit JVM which is happy to use that much memory.