【问题标题】:Error: open failed: ENOENT (No such file or directory)错误:打开失败:ENOENT(没有这样的文件或目录)
【发布时间】:2016-07-05 11:06:13
【问题描述】:

我试图创建一个文件来保存相机中的图片,结果我无法创建该文件。 但我真的找不到错误。你能看看它并给我一些建议吗?

    private File createImageFile(){
            File imageFile=null;
            String stamp=new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File dir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            String imageFileName="JPEG_"+stamp+"_";
            try {
                imageFile=File.createTempFile(imageFileName,".jpg",dir);
            } catch (IOException e) {
                Log.d("YJW",e.getMessage());
            }
            return  imageFile;
        }

我已经添加了权限。

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

方法老是报这样的错误:

打开失败:ENOENT(没有这样的文件或目录)

【问题讨论】:

  • example given in the API reference 有这一行:// Make sure the Pictures directory exists. path.mkdirs();。你确定目录已经存在吗?
  • 谢谢!在训练中没有这样的提示。我应该搜索 API 参考。谢谢!
  • @JiaweiYang 是我的建议奏效了吗?如果是这样,我会将其添加为答案。
  • 因为 Android 10 (Api level 29) 及更高版本不允许直接在外部存储中创建文件夹.. 您应该使用 getExternalFilesDir(Environment.DIRECTORY_PICTURES)

标签: android


【解决方案1】:

图片目录可能还不存在。它不保证在那里。

在the API documentation for getExternalStoragePublicDirectory()中,代码使用mkdirs确保目录存在:

File path = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

try {
    // Make sure the Pictures directory exists.
    path.mkdirs(); 

...所以它可能就像在 createTempFile 之前将 path.mkdirs() 添加到现有代码中一样简单。

【讨论】:

  • 需要检查新目录是否已创建 if (!path.mkdirs()) { Log.d("Un Available:" , path.getAbsolutePath()); }
  • getExternalStoragePublicDirectory(...) is depecratedString use this.getApplicationContext().getExternalFilesDir(null).toString();而是
【解决方案2】:

当用户从库中选择文件时,不能保证选择的文件是由其他应用添加或编辑的。因此,如果用户选择了一个属于另一个应用程序的文件,我们就会遇到权限问题。对此的快速解决方法是在 AndroidManifest.xml 文件中添加此代码:

<manifest ... >
  <application android:requestLegacyExternalStorage="true" ... >
    ...
  </application>
</manifest>

注意:对于 Android 11,请参阅范围存储强制政策https://developer.android.com/about/versions/11/privacy/storage

【讨论】:

  • 不幸的是,它不适用于 API 级别 30
  • Android 11 系统忽略 requestLegacyExternalStorage 标志,Scope Storage Android 11 android:preserveLegacyExternalStorage="true" 进行数据合并/移动。有关范围存储的更多详细信息,请参阅链接:developer.android.com/about/versions/11/privacy/storage 和 developer.android.com/training/data-storage#scoped-storage
  • android:preserveLegacyExternalStorage="true" 当用户将他/她的 android 操作系统更新到 11 时,您现有的 APP 需要。这样,您可以将数据从旧 DIR 传输到新 DIR WRT 11 范围存储策略。
【解决方案3】:

替换:

Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)

与:

private File createImageFile() throws IOException {
        // Create an image file name

请务必致电:

mkdirs() // and not mkdir()

以下是适合您的代码:

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = new File(Environment.getExternalStorageDirectory().toString(), "whatever_directory_existing_or_not/sub_dir_if_needed/");
        storageDir.mkdirs(); // make sure you call mkdirs() and not mkdir()
        File image = File.createTempFile(
                imageFileName,  // prefix
                ".jpg",         // suffix
                storageDir      // directory
        );

        // Save a file: path for use with ACTION_VIEW intents

        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        Log.e("our file", image.toString());
        return image;
    }

按照Android Studio Documentation 中给出的示例,我的体验很糟糕,我发现在stackoverflow 中还有很多其他人对这个特定主题有同样的体验,那是因为即使我们设置了

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

问题在某些设备中仍然存在。

我的经验是,当我在调试模式下尝试该示例时,该示例有效,之后又进行了 3 次测试,结果我的 SD 突然损坏,但我认为这与他们的示例无关(有趣)。我买了一张新的 SD 卡并再次尝试,才意识到发布和调试模式仍然出现相同的错误日志:目录不存在 ENOENT。最后,我必须自己创建目录,其中将包含从手机相机中捕获的图片。我是对的,它非常完美。

我希望这可以帮助您和其他寻找答案的人。

【讨论】:

  • 它不适用于 android 11
【解决方案4】:

对此的快速解决方法是在 AndroidManifest.xml 文件中添加此代码:

<manifest ... >
  <application android:requestLegacyExternalStorage="true" ... >
    ...
  </application>
</manifest>

注意:适用于 API 级别 29 或更高级别

【讨论】:

  • 这是 API 29 的临时解决方案,但它不适用于 API 30
【解决方案5】:

我将 contentResolver 与 URI 一起使用,它对我有用。在另一个我找不到的 SO 帖子中看到它。

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) {
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

希望对你有帮助....

【讨论】:

    【解决方案6】:

    我是这样解决的:

            public Intent getImageCaptureIntent(File mFile) {
                 Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                 Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", mFile);
                 mIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    
                 // The tip is this code below
                 List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(mIntent, PackageManager.MATCH_DEFAULT_ONLY);
                     for (ResolveInfo resolveInfo : resInfoList) {
                          String packageName = resolveInfo.activityInfo.packageName;
                          grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                     }
    
                 return  mIntent;
            }
    

    【讨论】:

      【解决方案7】:

      试试这个:

      private File createImageFile() throws IOException {  
      
          String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());  
      
          String imageFileName="JPEG_"+stamp+".jpg";  
      
          File photo = new File(Environment.getExternalStorageDirectory(),  imageFileName);  
      
          return photo;
      }  
      

      【讨论】:

        【解决方案8】:

        如果您使用的是 kotlin,请使用以下函数。 您必须提供用于存储图像的路径、位图(在本例中为图像),如果您想降低图像质量,则提供 %age 即 50%。

        fun cacheLocally(localPath: String, bitmap: Bitmap, quality: Int = 100) {
                val file = File(localPath)
                file.createNewFile()
                val ostream = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, ostream)
                ostream.flush()
                ostream.close()
            }
        

        希望它会起作用。

        【讨论】:

        • kotlin 与否在这里无关紧要。
        【解决方案9】:
        File dirPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = new File(dirPath, "YourPicture.jpg");
        
        try {
            if(!dirPath.isDirectory()) {
               dirPath.mkdirs(); 
            } 
            imageFile.createNewFile();
        
        } catch(Exception e) {
            e.printStackTrace();
        }
        

        【讨论】:

          【解决方案10】:

          我在将位图保存到外部目录时遇到了同样的错误,并找到了一个有用的技巧

          private void save(Bitmap bitmap) {
              String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
              String imageFileName = timeStamp + ".png";
              String path = MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap, imageFileName, null);
              Uri uriimage = Uri.parse(path);
              // you made it, make  fun
              }
          

          但这有一个缺点,即您无法更改目录,它总是将图像保存到图片目录,但如果您修复了它,请免费填充以编辑我的代码: 哈哈哈{我的键盘不能使用表情符号},美好的一天

          【讨论】:

          • 别忘了授予权限,否则我的帖子投反对票的可能性会增加
          【解决方案11】:

          以下是我找到的修复 首先在你的 AndroidManifest 文件中添加这两行

          在 setContentView 方法之后添加以下行

          ActivityCompat.requestPermissions(FullImageActivity.this,
                          new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                          REQUEST_CODE);
          

          为了将图像保存在图库中,请使用以下代码

          private void SaveImageToGallery() {
                  BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
                  Bitmap bitmap = drawable.getBitmap();
                  FileOutputStream outputStream = null;
                  File file = Environment.getExternalStorageDirectory();
                  File dir = new File(file.getAbsolutePath()+"/folderName");
                  dir.mkdirs();
                  String filename = String.format("%d.jpg",System.currentTimeMillis());
                  File outfile = new File(dir,filename);
                  try{
                      outputStream = new FileOutputStream(outfile);
                      bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                      outputStream.flush();
                      outputStream.close();
                  }catch(Exception e){
                      Log.d("SavingError", "SaveImageToGallery: "+e.getMessage());
                  }
                  Toast.makeText(this, "Image saved in folderName folder", Toast.LENGTH_SHORT).show();
              }
          

          【讨论】:

            猜你喜欢
            • 2013-02-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-08-23
            相关资源
            最近更新 更多