将文件转换为字节数组在Android中始终为空
问题描述:
我正在开发一个Android应用程序。在我的应用程序中,我需要将文件转换为字节数组。我尝试了一个堆栈溢出解决方案,它总是让我空。请参阅下面的代码。将文件转换为字节数组在Android中始终为空
这是我的onActivityResult回调
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();
}
}
我评论我在哪里在上面的代码转换文件的字节数组。上面的代码总是烘烤“NULL”消息。
这是我的转换方法
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;
}
}
为什么它总是空?如何正确地将文件转换为Android中的字节数组?
答
public static byte[] readBytes(InputStream inputStream) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream os = new ByteArrayOutputStream();
int c;
while ((c = inputStream.read(b)) != -1) {
os.write(b, 0, c);
}
return os.toByteArray();
}
可能重复? [文件到字节数组](http://stackoverflow.com/questions/858980/file-to-byte-in-java) – DrSatan1
很可能你遇到了一个异常。记录异常以找出错误。 – Henry
我得到这个错误 - /file:/storage/emulated/0/Download/147125382649668.pdf:打开失败:ENOENT(没有这样的文件或目录) 。 “file:/// storage”会自动转换为“file:/ storage”。请问我该如何解决这个问题@Henry –