-3

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();
    }
}
Shahabas Shakeer
  • 241
  • 1
  • 3
  • 13
  • 1
    Can you debug and say on which line your are getting FileNotFoundException – Abubakker Moallim Dec 20 '17 at 13:41
  • 2
    Edit your code to log exceptions to LogCat (e.g., `Log.e("AES-App", "Exception in creating file", e);`). Then, examine LogCat to determine where your problem is coming from. You do not need that Samsung check, but you do need to create your directory. Also, do not use string concatenation to create file paths, but instead use appropriate `File` constructors (e.g., `new File(Environment.getExternalStorageDirectory(), "SavedFiles")`. – CommonsWare Dec 20 '17 at 13:48
  • 1
    Also, you do not need `createNewFile()`, but you do need to [handle runtime permissions](https://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it). – CommonsWare Dec 20 '17 at 13:48
  • 1
    Did you request the permission at run time for newer Androids? – Henry Dec 20 '17 at 15:23
  • @ABDevelopers I have found that the file.createNewFile(); causes the exception. The exception raised was IOException. I apologize for the wrong information. I have also added code to request permission at run time. – Shahabas Shakeer Dec 20 '17 at 15:56
  • 1
    @AES that means your file is not getting created. – Abubakker Moallim Dec 20 '17 at 15:58
  • 1
    I think your directory is not created. – Abubakker Moallim Dec 20 '17 at 16:02
  • @CommonsWare I removed createNewFile() and now I am getting the FileNotFoundException : open failed : ENOENT. Does this has anything to do with how the storage should be accessed in newer API levels. I have already added code for requesting permission at run-time. – Shahabas Shakeer Dec 20 '17 at 16:20
  • @ABDevelopers Why wouldn't it get created? I have added permissions plus code to request permission on run-time. – Shahabas Shakeer Dec 20 '17 at 16:30

1 Answers1

1

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");
Abubakker Moallim
  • 1,610
  • 10
  • 20