I am developing an Android app. In my app I need to convert file into byte array. I tried a Stack Overflow solution and it is always giving me null.
This is my onActivityResult callback:
Uri bookUri = data.getData();
if(bookUri!=null)
{
String filePath = bookUri.toString();
String mime = app.getMimeType(filePath);
if(mime!=null && !mime.isEmpty() && (mime.toLowerCase()=="application/pdf" || mime.toLowerCase()=="application/txt" || mime.toLowerCase()=="application/text"))
{
bookFile = new File(filePath);
if(bookFile!=null)
{
byte[] bookByteArray = app.convertFileToByteArray(bookFile); //Converting file to byte array here
if(bookByteArray==null)
{
Toast.makeText(getBaseContext(),"NULL",Toast.LENGTH_SHORT).show();
}
}
//change book cover image
ivBookFile.setImageResource(R.drawable.book_selected);
}
else{
Toast.makeText(getBaseContext(),"Unable to process file you have chosen.",Toast.LENGTH_SHORT).show();
}
}
I commented where I am converting file to byte array in above code. The above code always toasting "NULL" message.
This is my convert method
public byte[] convertFileToByteArray(File file)
{
FileInputStream fileInputStream=null;
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
return bFile;
}catch(Exception e){
return null;
}
}
Why it is always null? How can I correctly convert file to byte array in Android?