VVB
VVB

Reputation: 7641

How to read file contents?

I am trying below code to select pdf from directory and read its contents but its not working

Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.setType("*/*");
        startActivityForResult(i, PICKFILE_RESULT_CODE);

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        switch(requestCode) {
            case PICKFILE_RESULT_CODE:
                if(resultCode==RESULT_OK){
//                    String filePath = data.getData().getPath();
//                    textViewFilePath.setText("File : " + filePath);
//                    readFromPdf(filePath);

                    StringBuilder text = new StringBuilder();
                    String filePath = data.getDataString();
                    try {
                        BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
                        String line;

                        while ((line = br.readLine()) != null) {
                            text.append(line);
                            text.append('n');
                        }
                        scanResults.setText(text + ".....");
                    }
                    catch (IOException e) {
                        //You'll need to add proper error handling here
                        e.printStackTrace();
                    }
                }
                break;

        }
    }

I am getting below exception

java.io.FileNotFoundException: content:/com.android.providers.downloads.documents/document/2295: open failed: ENOENT (No such file or directory)

Upvotes: 0

Views: 117

Answers (1)

greenapps
greenapps

Reputation: 11214

You should open an InputStream like

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

You should not try to use a reader or try to read lines.

Those do not make sense for a pdf file.

Upvotes: 1

Related Questions