我遇到了FileNotFoundException错误,但文件确实存在。

3

当我尝试通过Intent打开我选择的文件时,出现以下错误:

java.io.FileNotFoundException: /document/primary:Android/data/com.oli.myapp/Files/test.xml: open failed: ENOENT (没有这个文件或目录)

我不知道为什么会发生这种情况,因为我已经选择了该文件。这是我的代码:

文件选择:

Intent chooseFileXML = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(new Helper(FunctionsActivity.this).getPathToAppFolder());                
chooseFileXML.setDataAndType(uri, "text/xml");
Intent intentXML = Intent.createChooser(chooseFileXML, getString(R.string.importXMLDatei));
startActivityForResult(intentXML, REQUEST_CODE_IMPORT_XML_FILE);

获取代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    switch (requestCode){
        case REQUEST_CODE_IMPORT_XML_FILE:
            if(resultCode == RESULT_OK){

                String Fpath = data.getDataString();
                File file = new File(Fpath);
                Intent intent = new Intent(FunctionsActivity.this, CreateActivity.class);
                intent.setAction(Intent.ACTION_DEFAULT);
                intent.setData(Uri.parse(file.toURI().toString()));
                startActivity(intent);


            }
            break;
    }
}

编辑:

Uri uri = data.getData();
DocumentFile documentFile = DocumentFile.fromSingleUri(this, uri);
String type = documentFile.getType();
if(type.equals("text/xml")){
    try {
        InputStream inputStream = getContentResolver().openInputStream(uri);
        if(inputStream == null){
            throw new Exception();
        }
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line).append('\n');
        }

        //Could read the file with no problems
        createWithXMLCode(total.toString());

    }catch (Exception e){
        e.printStackTrace();
        //TODO

    }
}else{
    //TODO
}

请分享你的AndroidManifest.xml。 - ddb
1个回答

3

但是我在这里设置的类型 chooseFileXML.setDataAndType(uri, "text/xml"); 会让用户只能选择 XML 文件?! - XxGoliathusxX
@XxGoliathusxX:用户选择的XML文件不一定是一个文件。即使它确实是一个文件,也没有要求ACTION_GET_CONTENT返回带有file方案的Uri - CommonsWare
@XxGoliathusxX:“我正在通过查询创建一个ContentResolver”-- 我不知道你的意思。你可以通过在某个上下文(例如Activity)上调用getContentResolver()来创建ContentResolver - CommonsWare
我正在尝试遵循这三个不太清晰的步骤:
  1. 调用openInputStream()方法获取一个输入流来读取内容
  2. 调用getType()方法获取由该流支持的数据的MIME类型
  3. 调用query()方法,请求OpenableColumns,您可以在其中获取内容的大小和与内容相关联的某种人可识别的“显示名称”
- XxGoliathusxX
好的,我想我明白了。你能看一下我的编辑吗^^。这是一个可接受的解决方案还是有更好的方法? - XxGoliathusxX
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接