'reading a file from an intent produces FileNotFoundException

i want to read a file picked by an intent, but i always get a FileNotFoundException:

ActivityResultLauncher<Intent> resultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Uri uri = result.getData().getData();
    
                    try {
                        String content = "";
                        BufferedReader reader = new BufferedReader(new FileReader(new File(uri.getPath())));
                        while(true) {
                            String line = reader.readLine();
                            if(line == null) break;
                            content += line;
                        }
    
                        json = new JSONObject(content);
                        loadJSON();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
                }
            }
        }
     );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/json");

        resultLauncher.launch(intent);
    }

the exception occurs when initializing the FileReader. What is the correct way to read the file?



Solution 1:[1]

BufferedReader reader = new BufferedReader(new FileReader(new File(uri.getPath())));

uri.getPath() does not deliver a file system path which you could easily check if you used File.exists() on it.

You cannot use the File classes with an uri.

Better:

BufferedReader reader = new BufferedReader(getContentResolver().openInputStream(data.getData()))));
                

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blackapps