[英]Error: open failed: ENOENT (No such file or directory)
I was trying to create a file to save pictures from the camera, it turns out that I can't create the file.我试图创建一个文件来保存相机中的图片,结果我无法创建该文件。 But I really can't find the mistake.但我真的找不到错误。 Can you have a look at it and give me some advice?你能看看它并给我一些建议吗?
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;
}
And I have added the permission.我已经添加了权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The method always gives such mistakes:该方法总是会出现这样的错误:
open failed: ENOENT (No such file or directory)打开失败:ENOENT(没有那个文件或目录)
The Pictures directory might not exist yet.图片目录可能还不存在。 It's not guaranteed to be there.它不能保证在那里。
In the API documentation for getExternalStoragePublicDirectory()
, the code ensures the directory exists using mkdirs
:在getExternalStoragePublicDirectory()
的 API 文档中,代码使用mkdirs
确保目录存在:
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
...so it may be as simple as adding that path.mkdirs()
to your existing code before you createTempFile
. ...所以它可能就像在createTempFile
之前将该path.mkdirs()
添加到现有代码一样简单。
when a user picks a file from the gallery, there is no guarantee that the file that was picked was added or edited by some other app.当用户从图库中选择文件时,不能保证所选择的文件是由其他应用程序添加或编辑的。 So, if the user picks on a file that let's say belongs to another app we would run into the permission issues.所以,如果用户选择了一个文件,假设它属于另一个应用程序,我们就会遇到权限问题。 A quick fix for that is to add this code in the AndroidManifest.xml file:对此的快速解决方法是在 AndroidManifest.xml 文件中添加以下代码:
<manifest ... >
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
Note: Applicable for API level 29 or Higher注意:适用于 API 级别 29 或更高
Replace:替换:
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
With:与:
private File createImageFile() throws IOException {
// Create an image file name
make sure you call:确保你打电话:
mkdirs() // and not mkdir()
Here's the code that should work for you:这是应该适合您的代码:
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;
}
I had a bad experience following the example given in Android Studio Documentation and I found out that there are many others experiencing the same about this particular topic here in stackoverflow, that is because even if we set我在遵循Android Studio 文档中给出的示例时遇到了糟糕的经历,我发现在 stackoverflow 中还有许多其他人对这个特定主题有同样的经历,那是因为即使我们设置
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
the problem persists in some devices.该问题在某些设备中仍然存在。
My experience was that the example worked when I tried it in debug mode, after that 3 more tests it so happened that my SD suddenly was corrupted, but I don't think it has to do with their example (funny).我的经验是,当我在调试模式下尝试该示例时,该示例工作正常,经过 3 次更多测试后,我的 SD 突然损坏了,但我认为这与他们的示例无关(有趣)。 I bought a new SD card and tried it again, only to realize that still both release and debug mode did the same error log: directory does not exist ENOENT.我买了一个新的 SD 卡并再次尝试,才发现发布和调试模式仍然出现相同的错误日志:目录不存在 ENOENT。 Finally, I had to create the directories myself whick will contain the captured pictures from my phone's camera.最后,我必须自己创建目录,其中将包含从手机相机中捕获的图片。 And I was right, it works just perfect.我是对的,它完美无缺。
I hope this helps you and others out there searching for answers.我希望这可以帮助您和其他人在那里寻找答案。
A quick fix for that is to add this code in the AndroidManifest.xml file:对此的快速解决方法是在 AndroidManifest.xml 文件中添加以下代码:
<manifest ... > <application android:requestLegacyExternalStorage="true" ... > ... </application> </manifest>
Note: Applicable for API level 29 or Higher注意:适用于 API 级别 29 或更高
I used the contentResolver with the URI and it worked for me.我将 contentResolver 与 URI 一起使用,它对我有用。 Saw it in another SO post which i can't find.在我找不到的另一个 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;
}
hope it helps....希望它有帮助....
I have solved like this:我是这样解决的:
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;
}
Try this:试试这个:
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;
}
If you are using kotlin then use below function.如果您使用的是 kotlin,请使用以下功能。 you have to provide a path for storing image, a Bitmap (in this case a image) and if you want to decrease the quality of the image then provide %age ie 50%.你必须提供一个存储图像的路径,一个位图(在这种情况下是一个图像),如果你想降低图像的质量,那么提供 %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()
}
hope it will work.希望它会起作用。
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();
}
I got same error while saving Bitmap to External Directory and found a helpful trick我在将位图保存到外部目录时遇到了同样的错误,并找到了一个有用的技巧
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
}
But this have a drawback ie you cant change the Directory it always save images to Pictures directory but if you got it fixed fill free to edit my code: Haa-ha-ha {I can't use emojis with my keyboard}, Good Day但这有一个缺点,即您无法更改目录,它始终将图像保存到图片目录,但如果您修复了它,请免费填写以编辑我的代码:哈哈{我的键盘无法使用表情符号},美好的一天
Following are fixes i found first add these two lines in your AndroidManifest file以下是我发现首先在您的 AndroidManifest 文件中添加这两行的修复程序
Than add the below line just after setContentView method在 setContentView 方法之后添加以下行
ActivityCompat.requestPermissions(FullImageActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE);
and for saving the images in gallery use the below 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.