XxGoliathusxX XxGoliathusxX - 1 year ago 163
Android Question

Android Strange FileNotFoundException

When I try to open a file that I selected via an Intent I get this FileNotFoundException:

java.io.FileNotFoundException: /document/primary:Android/data/com.oli.myapp/Files/test.xml: open failed: ENOENT (No such file or directory)

I dont know why this happens. The file exists because I selected it.

Here is my Code:

//Select a file:

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);

Get it:

protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode){
if(resultCode == RESULT_OK){

String Fpath = data.getDataString();
File file = new File(Fpath);
Intent intent = new Intent(FunctionsActivity.this, CreateActivity.class);



Uri uri = data.getData();

DocumentFile documentFile = DocumentFile.fromSingleUri(this, uri);
String type = documentFile.getType();
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) {

//Could read the file with no problems

}catch (Exception e){


Answer Source

ACTION_GET_CONTENT gives you a Uri. What the user chooses through ACTION_GET_CONTENT does not have to be a file at all, let alone one you can access. In this case, you are getting a Uri back with a content scheme, which is very common.

Use a ContentResolver and methods like getInputStream() to work with the content represented by that Uri.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download