[英]File not found exception for text file which exists
我想用一个意图过滤器打开一个.txt文件,但是出现了这个异常
W / System.err:java.io.FileNotFoundException:文件:/存储/仿真/0/Download/ApplicationProposal.txt:打开失败:ENOENT(没有这样的文件或目录)
在以下行中:
FileInputStream fis = new FileInputStream(note);
路径例如是:
文件:///storage/emulated/0/Download/filename.txt
对于权限,我这样问:
public void requestWritePermissions() {
if(ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(getApplicationContext(), "Permission needed to export Notes to SD-Card!", Toast.LENGTH_LONG);
}
else{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_STORAGE);
}
}
}
在我的主要活动的onCreate()
中调用了它
编辑:更多信息:
这就是我调用读取文件的方法
File toOpen = new File(intent.getData().toString());
String text = noteHandler.loadNote(toOpen);
loadNote方法如下所示:
public String loadNote(File note){
String content = "";
try {
FileInputStream fis = new FileInputStream(note);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder data = new StringBuilder();
String line;
do{
line = reader.readLine();
if (line != null)
data.append(line).append("\n");
}
while (line != null);
content = data.toString();
reader.close();
fis.close();
} catch (Exception e){
e.printStackTrace();
Log.e("ERROR", e.toString());
}
return content;
}
您正在传递URL字符串,并尝试像使用路径名一样使用它。 操作系统自然会尝试将其解释为路径名...并且无法解析它。
假设您以URL开头,则应该执行以下操作:
URL toOpen = new URL(intent.getData().toString());
String text = noteHandler.loadNote(toOpen);
public String loadNote(URL note){
String content = "";
try {
InputStream is = note.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
....
请注意,用字符串重击“文件:” URL有点冒险:
(这些警告可能不适用于您的用例,但通常适用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.