Java 在android中选择文件后出现“找不到文件”错误
我想在我的android应用程序中打开一个.pdf文件。现在我可以浏览该pdf文件,浏览该文件后,当我检查该文件是否存在时,会发现未找到文件错误。现在,在选择文件之后,我选择的文件UriJava 在android中选择文件后出现“找不到文件”错误,java,android,pdf,android-intent,filenotfoundexception,Java,Android,Pdf,Android Intent,Filenotfoundexception,我想在我的android应用程序中打开一个.pdf文件。现在我可以浏览该pdf文件,浏览该文件后,当我检查该文件是否存在时,会发现未找到文件错误。现在,在选择文件之后,我选择的文件Uridata.getData()如下 content://com.android.externalstorage.documents/document/6333-6131:SHIDHIN.pdf 使用data.getData().getPath().toString()解析时的路径如下 /document/6333-
data.getData()
如下
content://com.android.externalstorage.documents/document/6333-6131:SHIDHIN.pdf
使用data.getData().getPath().toString()
解析时的路径如下
/document/6333-6131:SHIDHIN.pdf
这是我的代码。请帮帮我
// To Browse the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, PICK_FILE_REQUEST);
选择文件后
//onActivityResult
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case PICK_FILE_REQUEST:
if (resultCode == RESULT_OK) {
try {
Uri fileUri = data.getData();
String path = fileUri.getPath().toString();
File f = new File(path);
if (f.exists()) {
System.out.println("\n**** Uri :> "+fileUri.toString());
System.out.println("\n**** Path :> "+path.toString());
final Intent intent = new Intent(MainActivity.this, ViewPdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} else {
System.out.println("\n**** File Not Exist :> "+path);
}
} catch (Exception e) {
ShowDialog_Ok("Error", "Cannot Open File");
}
}
break;
}
} catch (Exception e) {
}
}
这不是答案,而是解决办法
File file = new File("some_temp_path"); # you can also use app's internal cache to store the file
FileOutputStream fos = new FileOutputStream(file);
InputStream is = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int len = 0;
try {
len = is.read(buffer);
while (len != -1) {
fos.write(buffer, 0, len);
len = is.read(buffer);
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
将此文件的绝对路径传递给您的活动。My.pdf文件可能会更改。用户可以从自己的设备上选择文件。如果文件存储在应用程序的内部缓存中,android不允许其他应用程序访问该文件。所以这可能就是问题所在。文件存储在外部目录中。您不能仅将uri转换为绝对路径。您需要使用
ContentResolver
。检查此答案@弗罗约也不适合我。我收到一个空指针异常“ava.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'char[]java.lang.String.toCharArray()”,这也不起作用。我们得到了空指针错误。我想是因为url的问题。当我们从url检索路径时,文件不存在错误正在得到。您从哪里得到错误?用logsHay更新问题对不起。。那是我的错误,我没有改变一些临时路径。现在它可以正常工作了。非常感谢。
File file = new File("some_temp_path"); # you can also use app's internal cache to store the file
FileOutputStream fos = new FileOutputStream(file);
InputStream is = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int len = 0;
try {
len = is.read(buffer);
while (len != -1) {
fos.write(buffer, 0, len);
len = is.read(buffer);
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}