Akash Aggarwal Akash Aggarwal - 6 months ago 38
Android Question

Android ENOENT error while trying to write a file

I've seen pretty many questions stating the same problem but I can't seem to figure out what's wrong with my code.

I'm new to using Uri's and don't really understand what's happening.

Firstly, the code which is responsible to start the activity for camera to take the pictures:

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);
}


Now the code where the problem arises:

@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) {

}
}
}

Answer

Make sure the path exists by calling mkdirs() before trying to create the file:

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);        
    ...
}

Don't forget the permission in the manifest:

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