首页 > 解决方案 > 卸载并重新安装后,Android App 抛出 FileNotFoundException

问题描述

我一直在 android studio 上开发一个需要访问文件来读取和写入密码的小应用程序。当我第一次测试它时它运行良好,但是当我卸载该应用程序并使用 apk 重新安装它时,它FileNotFound在 MainActivity 中抛出一个异常,在我第一次尝试访问该文件时。这是我在 MainActivity.java 中使用的代码:

                File fh = new File(getFilesDir().getPath(),"nothinghere.txt");
                Log.d("FileHandling","file exists "+fh.exists()+" file is directory "+ fh.isDirectory()+" file can be read "+fh.canRead()+" path "+fh.getAbsolutePath());
                try {
                    Log.d("FileHandling","Initializing InputStream");
                    InputStream inputStream = new FileInputStream(fh);
                    Log.d("FileHandling","InputStream success");
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    Log.d("FileHandling","BufferedReader success");
                    String password=reader.readLine();
                    Log.d("FileHandling","readLine success");
                    if(password==null){
                        Intent intent= new Intent(MainActivity.this, CreatePass.class);
                        startActivity(intent);
                    }
                    else{
                        Intent intent= new Intent(MainActivity.this, EnterPass.class);
                        startActivity(intent);
                    }
                } catch(FileNotFoundException e){
                    Log.d("FileHandling","File Not Found when retrieving password");
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.d("FileHandling","IOException when retrieving password");
                    e.printStackTrace();
                }

我有很多尝试调试它的日志。异常发生在InputStream inputStream = new FileInputStream(fh);。我将所有这些代码注释掉,并让 MainActivity 启动另一个活动,我在其中访问同一个文件,并且该活动也运行良好,直到我卸载应用程序并重新安装它(这次使用 android studio Run App 而不是 apk)我那次活动也有同样的问题。 这是我的java类所在的文件夹,我访问的txt文件都在同一个文件夹中。这是我得到的错误。

2020-06-04 19:46:32.156 17982-17982/com.example.calculator W/System.err: java.io.FileNotFoundException: /data/user/0/com.example.calculator/files/nothinghere.txt (No such file or directory)
2020-06-04 19:46:32.156 17982-17982/com.example.calculator W/System.err:     at java.io.FileInputStream.open0(Native Method)
2020-06-04 19:46:32.156 17982-17982/com.example.calculator W/System.err:     at java.io.FileInputStream.open(FileInputStream.java:231)
2020-06-04 19:46:32.156 17982-17982/com.example.calculator W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:165)

我认为这也是相关的,在第一次发生错误后,有时我会在应用更改时收到此警告:

Changes were not applied.
We were unable to deploy your changes: SETUP_FAILED

此外,当我尝试取消注释 MainActivity 上的行以访问文件时,它仍然会引发相同的异常和错误。这是一个非常奇怪的问题,我没有很多使用 android 的经验,我找不到任何描述我的问题的东西,所以我非常感谢一些帮助。

标签: javaandroidandroid-studiofilenotfoundexception

解决方案


推荐阅读