javaandroidioexceptionfileoutputstreamnosuchfileexception

android creating .txt and .csv files throwing ENOENT No such file or directory exception


I've created an app and i'm just adding in the feature to export data as a .txt or .csv file but I'm getting an error on file creation. The error in logcat appears as File write failed: java.io.IOExcepion: open failed: ENOENT (NO such file or directory).
Can anyone see where i'm making a mistake?
I call the writeToFile() method passing either String txt; or String csv; into it depending on which file type is needed.
code:

 String txt = ".txt";
 String csv = ".csv";

 private void writeToFile(String fileType) {



        // if file name has not been entered...
        if (filename.equals("")||filename.equals(null)) {

            //display toast
            toastMsg = "Please enter a file name";
            toast();

        }

        // else if file name has been entered...
        else if (!filename.equals("")) {

            // create FileCheck
            File fileCheck = new File("/sdcard/" + filename + fileType);

            // if file exists...
            if (fileCheck.exists()) {

                // display toast
                toastMsg = "Export Error: File already exists";
                toast();


            }

            // if file does not exist...
            else if (!fileCheck.exists()) {


                try {

                    // create file
                    File myFile = new File("/sdcard/" + filename + fileType);

                    myFile.createNewFile();
                    FileOutputStream fOut = new FileOutputStream(myFile);
                    OutputStreamWriter myOSW = new OutputStreamWriter(fOut);
                    myOSW.append("file data here");
                    myOSW.close();
                    fOut.close();

                    // display toast
                    toastMsg = "file created: " + myFile.toString();
                    toast();

                }
                catch (IOException e) {
                    Log.e(TAG, "File write failed: " + e.toString());
                    toastMsg = "file write failed: " +e.toString();
                    toast();
                }

           }    
        }
    }

Solution

  • This path doesn't exist:

    File myFile = new File("/sdcard/" + filename + fileType);
    

    Maybe you mean:

    File myFile = new File("/mnt/sdcard/" + filename + fileType);
    

    Which on some devices may not exist as well (sometimes these linked paths are called sdcard0, sdcard1, external_storage, ...)

    You'd better use

    File myFile = new File(Environment.getExternalStorageDirectory() + "/" + filename + fileType);
    

    And make sure you set the permission

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

    In your manifest, which also includes the READ_EXTERNAL_STORAGE permission