Android Create String from XML-filepath



在我的应用程序中,用户可以通过Intent选择xml文件:

选择:

Intent chooseFileXML = new Intent(Intent.ACTION_GET_CONTENT);
chooseFileXML.setType("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){
                    Uri uri = data.getData();
                    String filePath = uri.getPath();
                    File fl = new File(filePath);
                    //Get xml-code from file and put it in a String
                    FileInputStream fin = null;
                    try {
                    fin = new FileInputStream(fl);
                    BufferedReader reader = new BufferedReader(new  InputStreamReader(fin));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line).append("n");
                    }
                    reader.close();
                    System.out.println(sb.toString());
                    fin.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
             }
             break;
        }
    }

我收到正确的文件路径。但在这一行中:fin = new FileInputStream(fl);我收到此错误:

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

文件路径中的实际问题.您的文件路径无效,因此请找到文件的真实路径

 String filePath = getRealPathFromURI(uri);

getRealPathFromURI 方法

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
 }

相关内容

  • 没有找到相关文章

最新更新