【问题标题】:Getting Error while creating file创建文件时出错
【发布时间】:2016-10-28 07:10:19
【问题描述】:
public void saveByteArrayToFile(Context context){
        Log.v(TAG, "Save byte array to file");
        switch(mType){
            case ChatMessage.AUDIO_MESSAGE:
                filePath = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_MUSIC).getAbsolutePath()+"/"+fileName;
                break;
            case ChatMessage.VIDEO_MESSAGE:
                filePath = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_MOVIES).getAbsolutePath()+"/"+fileName;
                break;
            case ChatMessage.FILE_MESSAGE:
                filePath = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+"/"+fileName;
                break;
            case ChatMessage.DRAWING_MESSAGE:
                filePath = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/"+fileName;
                break;
        }
        System.out.println("Mera path"+filePath);
        File file = new File(filePath);

        if (file.exists()) {
            file.delete();
        }

        try {
            FileOutputStream fos=new FileOutputStream(file.getPath());

            fos.write(byteArray);
            fos.close();
            Log.v(TAG, "Write byte array to file DONE !");
        }
        catch (java.io.IOException e) {
            e.printStackTrace();
            Log.e(TAG, "Write byte array to file FAILED !");
        }
    }

java.io.FileNotFoundException: /storage/sdcard0/Android/data/... 原因:android.system.ErrnoException: open failed: ENOENT (No such file or directory)

我在创建文件时收到此错误。

【问题讨论】:

  • 也许您没有写入该路径的权限?

标签: java android filenotfoundexception fileoutputstream


【解决方案1】:

所以,文件存在。然后会发生这种情况:

if (file.exists()) {
    file.delete();
}

现在它不存在,所以你不能使用:

file.getPath();

改用这个:

FileOutputStream fos=new FileOutputStream(filePath);

【讨论】:

    【解决方案2】:

    不确定您是否已经这样做了,但您需要在清单中声明您的应用将写入外部存储(如果针对 apk 版本 23+,您还需要请求用户接受在将这些权限授予您的应用之前)。

    在清单中的应用程序标签内添加这一行:

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

    如果面向 SDK 版本 23+,您需要请求运行时权限,详见 https://developer.android.com/training/permissions/requesting.html

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多