Android 无法解码流 java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25467007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:27:14  来源:igfitidea点击:

unable to decode stream java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory

androideclipsetimerandroid-cameracapture

提问by Andonirock

hello i'm trying to save pictures taken on my application, but when i try to access the memory to place the data, an error comes out

你好,我正在尝试保存在我的应用程序上拍摄的照片,但是当我尝试访问内存以放置数据时,出现错误

unable to decode stream java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory)

无法解码流 java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory)

this is my code.

这是我的代码。

            Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub
            if (data != null){
                //Intent mIntent = new Intent();
                //mIntent.putExtra("image",imageData);

                mCamera.stopPreview();
                mPreviewRunning = false;
                mCamera.release();

                 try{
                     BitmapFactory.Options opts = new BitmapFactory.Options();
                     Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
                     bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
                     int width = bitmap.getWidth();
                     int height = bitmap.getHeight();
                     int newWidth = 300;
                     int newHeight = 300;

                     // calculate the scale - in this case = 0.4f
                     float scaleWidth = ((float) newWidth) / width;
                     float scaleHeight = ((float) newHeight) / height;

                     // createa matrix for the manipulation
                     Matrix matrix = new Matrix();
                     // resize the bit map
                     matrix.postScale(scaleWidth, scaleHeight);
                     // rotate the Bitmap
                     matrix.postRotate(-90);
                     Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                             width, height, matrix, true);
                     Camera_local_db.image.setImageBitmap(resizedBitmap);

                 }catch(Exception e){
                     e.printStackTrace();
                 }
               // StoreByteImage(mContext, imageData, 50,"ImageName");
                //setResult(FOTO_MODE, mIntent);
                setResult(585);
                finish();
            }       
        }
    };


    Camera.PictureCallback jpegCallback = new Camera. PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {


        File dir_image2 = new  File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"dddd.jpg");
        dir_image2.mkdirs();  //AGAIN CHOOSING FOLDER FOR THE PICTURE(WHICH IS LIKE A SURFACEVIEW 
                                //SCREENSHOT)
        if (!dir_image2.mkdirs()) {
            Log.e(TAG, "Directory not created");
        }


        File tmpFile = new File(dir_image2,"TempGhost.jpg"); //MAKING A FILE IN THE PATH                 
                        //dir_image2(SEE RIGHT ABOVE) AND NAMING IT "TempGhost.jpg" OR ANYTHING ELSE
        try {//SAVING
            FileOutputStream fos = new FileOutputStream(tmpFile);
            fos.write(data);
            fos.close();
            //grabImage();
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
        }
        //String path = Environment.getExternalStoragePublicDirectory(    Environment.DIRECTORY_MOVIES); File file = new File(path, "/" + dir_image2);
        //String path = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+  
          //      File.separator+"TempGhost.jpg");//<---

        BitmapFactory.Options options = new BitmapFactory.Options();//<---
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;//<---
        bmp1 = BitmapFactory.decodeFile(tmpFile.toString(), options);//<---
        //THE LINES ABOVE READ THE FILE WE SAVED BEFORE AND CONVERT IT INTO A BitMap
        Camera_local_db.image.setImageBitmap(bmp1);
        //camera_image.setImageBitmap(bmp1); //SETTING THE BitMap AS IMAGE IN AN IMAGEVIEW(SOMETHING
                                    //LIKE A BACKGROUNG FOR THE LAYOUT)
       // TakeScreenshot();//CALLING THIS METHOD TO TAKE A SCREENSHOT

    }
    };

回答by Jairo Correa

You need to write to external storage, make sure you added the permission:

您需要写入外部存储,确保您添加了权限:

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

Checks if external storage is available for read and write:

检查外部存储是否可用于读写:

public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

Use the root of the public directory instead of using the root of Android.

使用公共目录的根目录,而不是使用 Android 的根目录。

If you want to save public files on the external storage, use the getExternalStoragePublicDirectory()

如果要将公共文件保存在外部存储上,请使用 getExternalStoragePublicDirectory()

public File getAlbumStorageDir(String albumName) {
    // Get the directory for the user's public pictures directory. 
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

If you want to save files that are private to your app, use the getExternalFilesDir()

如果要保存应用程序私有的文件,请使用 getExternalFilesDir()

public File getAlbumStorageDir(Context context, String albumName) {
    // Get the directory for the app's private pictures directory. 
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_DCIM), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

More information on the link http://developer.android.com/training/basics/data-storage/files.html

有关链接的更多信息http://developer.android.com/training/basics/data-storage/files.html

回答by Calixto

I had the same error, and the only problem was the permission in android manifest.

我有同样的错误,唯一的问题是 android manifest 中的权限。

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


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

回答by CommonsWare

First, you are writing the image to a different location than you are reading it from. Rather than rebuild path, use the tmpFilevalue that you already have.

首先,您将图像写入与读取图像不同的位置。而不是重建path,使用tmpFile你已经拥有的价值。

Second, do not use getRootDirectory()to get the DCIMdirectory. Use getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).

二、不要使用getRootDirectory()来获取DCIM目录。使用getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).

Third, use Logmethods to log exceptions, rather than just display a Toast, as you may miss the Toastand you do not get the stack trace associated with your exception.

第三,使用Log方法记录异常,而不仅仅是显示Toast,因为您可能会错过Toast并且您不会获得与异常相关的堆栈跟踪。

回答by HymanTurky

I solved using this:

我用这个解决了:

private static final int WRITE_PERMISSION = 0x01;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestWritePermission();
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if(requestCode == WRITE_PERMISSION){
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.d(LOG_TAG, "Write Permission Failed");
            Toast.makeText(this, "You must allow permission write external storage to your mobile device.", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}

private void requestWritePermission(){
    if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},WRITE_PERMISSION);
    }
}

回答by Annada

Add this permission in Android Manifest.

在 Android Manifest 中添加此权限。

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

If it fails with this permission is present already, then you need to check your app's target SDK level. If it is targetSdkVersion => 23, then you need to request permissions at Run Time. Here

如果此权限已存在而失败,则您需要检查应用程序的目标 SDK 级别。如果是targetSdkVersion => 23,则需要在运行时请求权限。 这里