Java reading file to a byte array - most efficient implementation
Im reading image files off an sdcard of an android device. This results in an out of memory fatal error due to a memory leak. I have narrowed it down to an allocation of 1 byte arrays that are not be开发者_StackOverflow社区ing removed by the GC. I use FileInputStream to read in the file is there a more efficient way to do this? Can you see the cause of the memory leak? Thanks
private String getHexFileString(File _file)
{
byte[] byteStream = new byte[(int) _file.length()];
String fileHexString = null;
try
{
FileInputStream fis = new FileInputStream(_file);
fis.read(byteStream);
fis.close();
fis = null;
fileHexString = byteArrayToHexString(byteStream);
}
catch (FileNotFoundException e1)
{ actLog.addMessage(new ErrorMessage(e1)); }
catch (IOException e2)
{ actLog.addMessage(new ErrorMessage(e2)); }
catch(OutOfMemoryError e3)
{ actLog.addMessage(new ErrorMessage(e3)); }
return fileHexString;
}
/**
* This method formats a byte-array into a hex string
*
* @param b byte-array
* @return hex string
*/
public String byteArrayToHexString(byte[] b)
{
char[] hexVal = new char[b.length * 2];
int value = 0;
for (int i = 0; i < b.length; i++)
{
value = (b[i] + 256) % 256;
hexVal[i * 2 + 0] = kDigits[value >> 4];
hexVal[i * 2 + 1] = kDigits[value & 0x0f];
}
return new String(hexVal);
}
If some exception occure while you read you will not close the file. It's better to use block finally
You are likely to find that converting to a hex String is far more expensive in time and memory than reading the file. i.e. the String will be 4x bigger.
If you want to improve efficiency and avoid running out of memory you should use a method which returns a byte[] and you operate on this array.
精彩评论