在我的应用中,用户可以通过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(没有这样的文件或目录)
答案 0 :(得分:0)
实际上文件路径有问题。你的文件路径不是vaild所以找到文件的真实路径
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;
}