且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找不到文件的错误选择在android系统文件后

更新时间:2023-11-22 17:58:16

这是没有答案,但一个解决办法。

 文件fil​​e =新的文件(some_temp_path); #你也可以使用应用程序的内部缓存来存储文件
FOS的FileOutputStream =新的FileOutputStream(文件);。InputStream为= context.getContentResolver()openInputStream(URI);
字节[]缓冲区=新的字节[1024];
INT LEN = 0;
尝试{
    LEN = is.​​read(缓冲液);
    而(LEN!= -1){
        fos.write(缓冲液,0,LEN);
        LEN = is.​​read(缓冲液);
    }    fos.close();
}赶上(IOException异常五){
    e.printStackTrace();
}

通过这个文件的绝对路径到您的活动。

I want to open a .pdf file in my android app.now i can browse the pdf file and after browsing the file I am getting File Not Found Error when i check the file exist or not. Now after selecting the file my selected file Uri data.getData() is like

content://com.android.externalstorage.documents/document/6333-6131:SHIDHIN.pdf

and the path when i parse using data.getData().getPath().toString() is like

/document/6333-6131:SHIDHIN.pdf Here is my code. Please Help me.

// To Browse the file

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, PICK_FILE_REQUEST);

After selecting file

//onActivityResult

public void onActivityResult(final int requestCode, int resultCode, Intent data) {
    try {
        switch (requestCode) {
            case PICK_FILE_REQUEST:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri fileUri = data.getData();
                        String path  = fileUri.getPath().toString();
                        File f = new File(path);
                        if (f.exists()) {
                            System.out.println("\n**** Uri :> "+fileUri.toString());
                            System.out.println("\n**** Path :> "+path.toString());
                            final Intent intent = new Intent(MainActivity.this, ViewPdf.class);
                            intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
                            startActivity(intent);
                        } else {
                            System.out.println("\n**** File Not Exist :> "+path);
                        }

                    } catch (Exception e) {
                        ShowDialog_Ok("Error", "Cannot Open File");
                    }
                }
                break;
        }
    } catch (Exception e) {
    }
}

This is not the answer but a workaround.

File file = new File("some_temp_path"); # you can also use app's internal cache to store the file
FileOutputStream fos = new FileOutputStream(file);

InputStream is = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int len = 0;
try {
    len = is.read(buffer);
    while (len != -1) {
        fos.write(buffer, 0, len);
        len = is.read(buffer);
    }

    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

pass this file's absolute path to your activity.