MyNameIsGuzse
MyNameIsGuzse

Reputation: 293

FileNotFoundException on FileReader

My application needs to select a .txt document, open it, and read it line by line. I can get the file path no problem, but FileReader won't open the file, throwing a FileNotFoundException.

My Code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case ACTIVITY_CHOOSE_FILE: {
            if (resultCode == RESULT_OK){
                Uri uri = data.getData();
                filePath = uri.getPath();
                if (filePath != ""){
                    txtvFileSelected.setText(filePath);
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(filePath);
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = null;
                                new BufferedReader(fileReader);
                        int currentLine = 0;
                        while((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            //TODO: add string separation into floats here.
                            currentLine++;
                        }
                        // Always close files.
                        bufferedReader.close();
                    }
                    catch(FileNotFoundException ex) {
                        System.out.println("File not found '" + filePath + "'");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else
                    txtvFileSelected.setText("No file selected");
            }
        }
    }
}

Error Log:

05-14 09:14:51.409 24212-24279/com.examens.gilian.robotapplication OpenGLRenderer: Initialized EGL, version 1.4
05-14 09:14:53.428 24212-24279/com.examens.gilian.robotapplication D/OpenGLRenderer: endAllActiveAnimators on 0xb8ad5368 (RippleDrawable) with handle 0xb8988670
05-14 09:14:59.046 24212-24212/com.examens.gilian.robotapplication I/System.out: File not found '/document/primary:media/Data.txt'

Upvotes: 0

Views: 74

Answers (1)

greenapps
greenapps

Reputation: 11224

filePath = uri.getPath();

That is not a file system path so no wonder that nothing can be found.

Instead open an input stream and read from the stream.

InputStream is = getContentResolver().openInputStream(data.getData());

Upvotes: 1

Related Questions