java - android 创建 .txt 和 .csv 文件抛出 ENOENT No such file or directory 异常

标签 java android ioexception fileoutputstream nosuchfileexception

我创建了一个应用程序,只是添加了将数据导出为 .txt 或 .csv 文件的功能,但我在创建文件时遇到错误。 logcat 中的错误显示为文件写入失败:java.io.IOExcepion:打开失败:ENOENT(没有此类文件或目录)
任何人都可以看到我在哪里犯了错误吗?
我调用 writeToFile() 方法传递 String txt;或字符串 csv;根据需要的文件类型进入其中。
代码:

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

           }    
        }
    }

最佳答案

该路径不存在:

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

也许你的意思是:

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

在某些设备上可能不存在(有时这些链接路径称为 sdcard0、sdcard1、external_storage...)

你最好使用

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

并确保您设置了权限

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

在您的 list 中,其中还包含READ_EXTERNAL_STORAGE权限

关于java - android 创建 .txt 和 .csv 文件抛出 ENOENT No such file or directory 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25380077/

相关文章:

java - 使用 JPA 的 Spring Boot OnetoMany

java - 从数据库字段声明新路线

java - Actionbar Overflow 中的单元测试菜单项

android - 自定义偏好 Android Kotlin

java - 使用不同用户执行jstack导致Full GC

java - 如何从 Spring Data JPA GROUP BY 查询中返回自定义对象

android camera2 api - 一起录制视频声音和麦克风

java - IOException 和 FileNotFoundException

android - 在 Android Studio 终端中运行时出现 IO 异常

安卓 ADK : IO Exception (ENODEV)