尝试写入文件时出现Android ENOENT错误

时间:2016-05-23 20:59:25

标签: java android file-handling

我看到很多问题都说明了同样的问题,但我似乎无法弄清楚我的代码有什么问题。
我刚开始使用Uri并且不太了解发生了什么 首先,代码负责启动相机拍摄照片的活动:

void cameraAction() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
    startActivityForResult(intent, 1);
    }

现在出现问题的代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);

                viewImage.setImageBitmap(bitmap);

                String path = Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                OutputStream outFile;
                String fileName = "" + System.currentTimeMillis() + ".jpg";
                File file = new File(path, fileName);
                try {//This is where the ENOENT error is shown
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {

        }
    }
}

1 个答案:

答案 0 :(得分:1)

在尝试创建文件之前,请通过调用mkdirs()确保路径存在:

String path = Environment
        .getExternalStorageDirectory()
        + File.separator
        + "Phoenix" + File.separator + "default";

if (new File(path).mkdirs()) {
    OutputStream outFile;
    String fileName = "" + System.currentTimeMillis() + ".jpg";
    File file = new File(path, fileName);        
    ...
}

不要忘记清单中的许可:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />