context.openFileInput() returning null when trying to access a stored file

删除回忆录丶 提交于 2019-12-12 16:42:39

问题


Currently, I have the following code for saving a Web Archive and then getting it as a FileInputStream. However, the channel within webContent remains null and a FileNotFoundException is thrown:

        // Save the Web Archive once loading is finished
        String path = context.getFilesDir().getAbsolutePath()
                + File.separator + WEB_PREFIX + postId;
        webView.saveWebArchive(path);
        FileInputStream webContent = null;
        try {
            webContent = context.openFileInput(WEB_PREFIX + postId);
        } catch (FileNotFoundException e) {
            Log.d("onPageFinished()", "FileNotFoundException");
            e.printStackTrace();
        }

If I try to perform context.openFileInput(path) instead, I get

09-05 23:39:42.448: E/AndroidRuntime(8399): java.lang.IllegalArgumentException: File /data/data/com.example/files/web-2189241737372651547 contains a path separator

Does anyone know of a solution? The file certainly exists, since I saved it in the previous line.


回答1:


openFileInput() doesn't accept paths, only a file name if you want to access a path.

Use this instead:

File file = new File(this.getFilesDir().getAbsolutePath() + (WEB_PREFIX + postId));

EDIT: You need to make sure you are saving and retrieving the file from the same place. Give this a go:

Note: I'm not sure you need File.separator but try with and without it and see which one works.

 String path = context.getFilesDir().getAbsolutePath()
                + File.separator + WEB_PREFIX + postId;
        webView.saveWebArchive(path);
        FileInputStream webContent = null;
        try {
            webContent = new File(path);
        } catch (FileNotFoundException e) {
            Log.d("onPageFinished()", "FileNotFoundException");
            e.printStackTrace();
        }


来源:https://stackoverflow.com/questions/18649543/context-openfileinput-returning-null-when-trying-to-access-a-stored-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!