FileNotFoundException - 创建文件并保存到外部存储时。 - Android

时间:2017-06-16 20:27:18

标签: java android file android-fragments android-activity

我正在尝试将文件保存到外部存储,但是它会给出FileNotFoundException错误。

注意:我已经对Android Manifest进行了更改。

        File file = null;
        if (isExternalStorageWritable()) {
          Log.d("SEND", "Entrou no IF do ExernalStorage");
          //File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
          File path = ContaListFragment.this.getActivity()
                                     .getApplicationContext()
                                     .getExternalFilesDir(
          Environment.DIRECTORY_PICTURES);//getExternalFilesDir
          file = new File(path, "file.json");

          //Make sure the Pictures directory exists.
          Log.d("SEND", "" + path.mkdir() + " PATH=" + file.getAbsolutePath());
          //file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "file.json");
        }

        if (!file.mkdirs()) {
           Log.d("SEND", "Directory not created");
        }

        if (!isExternalStorageWritable()) {
           file = new File(ContaListFragment.this.getActivity()
                    .getApplicationContext().getFilesDir(), "file.json");
           Log.d("SEND", "Passei do File");
           output = new BufferedWriter(new FileWriter(file));
           Log.d("SEND", "Passou do Buffered");
           output.write(jsonObject.toString());
           uri = Uri.fromFile(file);
        }

1 个答案:

答案 0 :(得分:0)

在以下情况的帮助下解决了这个问题: See the answers to this question

问题是我正在创建目录而不是文件。只需替换:file.mkdirs(); with file.createNewFile();