得到一个奇怪的 filenotfoundexception

Getting a weird filenotfoundexception

就 Android 而言,我目前处于初学者水平,而且我目前正在为我目前面临的问题而绞尽脑汁。

我正在创建一个 Android 应用程序来检查 "cache.json" 是否存在于内部存储中:

这是代码片段:

public class ShowClasses extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        filename = "cache.json";
        file = new File(getApplicationContext().getFilesDir(), filename);

        if (file.exists()) {
            System.out.println("EXISTS");
        } else {
            System.out.println("DOES NOT EXIST");
            writeFile();
        }

        readFile();
    }

    public void writeFile() {
        new JsonTask().execute(email);
    }

    public void readFile() {
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int c;
        result = "";
        try {
            while( (c = fin.read()) != -1){
                result = result + Character.toString((char)c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }

    private class JsonTask extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
            result = ""; // Clear result
            super.onPreExecute();
            pd.setMessage("Please wait");
            pd.setCancelable(false);
            pd.show();
        }

        protected String doInBackground(String... params) {
            return "THIS STRING IS GOING TO BE RETURNED " + params[0];
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);    

            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            FileOutputStream fileout = null;

            try {
                fileout = new FileOutputStream(file);
                fileout.write(result.getBytes());
                //display file saved message
                msg("File saved successfully!");

            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                fileout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (pd.isShowing()){
                pd.dismiss();
            }

        }
    }
}

我已尝试删除代码中不需要的部分,以使其长度更小。

我面临的实际问题是调用 writeFile() 和 readFile() 时。当我打开流时,我在 readFile() 中得到一个 FileNotFoundException,即使应该创建文件,因为在 readFile() 之前调用了 writeFile()。

如果我在一次执行中写入文件,然后在另一次执行中调用 readFile(),它会按预期工作。

这是我面临的错误。

System.err: java.io.FileNotFoundException: /data/user/0/host.timetable.timetablenotifier/files/cache.json (No such file or directory) System.err: at java.io.FileInputStream.open(Native Method)

任何帮助将不胜感激。

谢谢

AsyncTask 在后台线程中运行,因此主线程中的其他代码不会等待执行完成。简单来说,您的 readFile() 方法在 writeFile() 完成之前执行,因此存在 FileNotFoundException。如果您将 readFile() 方法放在 onPostExecute() 方法的末尾,那么对您有用的是 Asynctask

writeFile() 是异步的。当该方法 returns、关于此文件时没有发生任何事情。最多可以调用 JsonTask 中的 onPreExecute()。因此,当您调用 readFile() 时,该文件还不存在。

除此之外:

  • 您在 writeFile() 中使用了一个 AsyncTask,但是您在 onPostExecute() 中使用了磁盘 I/O,并且该方法被称为在主应用程序线程上。

  • 您正在 readFile().

  • 中的主应用程序线程上执行磁盘 I/O
  • 你捕获异常,记录它们,然后继续执行你的代码,当大多数异常意味着后面的语句也会失败时。

  • 出于性能原因,一次读取一个 int 数据并不是接近 20 年的推荐方法。

  • 您将遇到多个与配置更改相关的问题,例如屏幕旋转,因为您的 AsyncTaskProgressDialog 都不会考虑配置更改

还有:

  • getApplicationContext().getFilesDir() 可以在 onCreate()

  • 中替换为 getFilesDir()
  • 你不需要createNewFile()