我想用intent-filter打开一个.txt文件,但是我得到了这个异常
W / System.err:java.io.FileNotFoundException:file:/storage/emulated/0/Download/ApplicationProposal.txt:open failed: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;
}
答案 0 :(得分:1)
您正在传递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有点冒险:
(这些警告可能不适用于您的用例,但一般情况下都适用)