我收到一个FileNotFoundException,但文件在那里

时间:2016-07-10 21:22:22

标签: java android xml file android-intent

当我尝试打开通过Intent选择的文件时,我收到此错误:

  

java.io.FileNotFoundException:   /document/primary:Android/data/com.oli.myapp/Files/test.xml:open   失败: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
}

1 个答案:

答案 0 :(得分:2)

ACTION_GET_CONTENT为您提供Uri。用户通过ACTION_GET_CONTENT选择的内容根本不必是文件,更不用说您可以访问的文件了。在这种情况下,您将获得Uri一个content方案,这很常见。

Use a ContentResolver and methods like getInputStream()使用Uri所代表的内容。

相关问题