【发布时间】:2016-08-19 10:00:16
【问题描述】:
我正在开发一个 Android 应用程序。在我的应用程序中,我需要将文件转换为字节数组。我尝试了 Stack Overflow 解决方案,但它总是给我 null。
这是我的 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 中正确地将文件转换为字节数组?
【问题讨论】:
-
可能重复? File to byte array
-
您很可能遇到了异常。记录异常以找出问题所在。
-
我收到此错误 - /file:/storage/emulated/0/Download/147125382649668.pdf: open failed: ENOENT (No such file or directory) 。 "file:///storage" 自动转换为 "file:/storage" 。请问我该如何解决这个问题@Henry
-
在
file:之前真的有/吗?这不应该在那里。此外,该文件是否真的存在于该位置,您的进程是否具有访问权限?此外,File构造函数需要文件名而不是 URL。 -
是的。这是完整的日志 EXCEPTION_SMS:/file:/storage/emulated/0/Download/147125382649668.pdf:打开失败:ENOENT(没有这样的文件或目录)