Search code examples
javaandroidioexceptionandroid-external-storageenoent

How do I write to and read from External Storage directory of all devices?


I have a problem with writing files to the external storage directory. I have added the permissions. The code works fine in some devices while it crashes in others. The error I get is a java.io.IOException: open failed: ENOENT (No such file or directory). I want every device and every Android version to run this code and save the file to external storage as needed.

Here's the code:

    public void createFile(View v) {
        requestPermission();
        String fileLocation = Environment.getExternalStorageDirectory().getPath() + "/SavedFiles";
        String fileContent = getFileContent();
        //Check for samsung devices because they require a different method of storage access
        if(android.os.Build.DEVICE.contains("Samsung") || android.os.Build.MANUFACTURER.contains("Samsung")){
            fileLocation = fileLocation + "/external_sd/";
        }
        try {
            File file = new File(fileLocation, "newfile.txt");
            if (!file.exists()) {
                file.createNewFile();
                FileOutputStream fOut = new FileOutputStream(file);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                myOutWriter.append(fileContent);
                myOutWriter.close();
                fOut.close();
                Toast.makeText(this, "File created!", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Could not create the file.", Toast.LENGTH_LONG).show();
        }
    }

public void requestPermission(){
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
        } else {
            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }
    else {
        Log.v(TAG,"Permission is granted");
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        createFile();
    }
}

Solution

  • Try replacing your code with this

    File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/SavedFiles", "");
        if (!fileDirectory.exists())
                {
                    fileDirectory.mkdirs();
                }
        File file = new File(fileDirectory, "newfile.txt");