java.io.FileNotFoundException:mounted / saved_images / Image-6999.jpg(没有这样的文件或目录)

时间:2017-02-08 09:31:43

标签: android android-layout android-studio

我通过点击按钮在Android中创建截图,但无法保存图像。我在“没有这样的文件或目录”中有一条错误消息。我该怎么办?

我的代码:

 public class MainActivity extends Activity {
    LinearLayout L1;
    ImageView image;
    Bitmap bm;
    File file;
    FileOutputStream fileoutputstream;
    View v1;
    ByteArrayOutputStream bytearrayoutputstream;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bytearrayoutputstream = new ByteArrayOutputStream();
        L1 = (LinearLayout) findViewById(R.id.layout);
        Button but = (Button) findViewById(R.id.Button01);
        but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    View v1 = L1.getRootView();
                    v1.setDrawingCacheEnabled(true);
                    Bitmap bm = v1.getDrawingCache();
                    BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                    image = (ImageView) findViewById(R.id.ImageView02);
                    image.setBackgroundDrawable(bitmapDrawable);

                    Log.e("top-->", String.valueOf(bitmapDrawable));



                    bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);

                    //String path = Environment.getExternalStorageDirectory().toString();
                    File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
                    myDir.mkdirs();
                    Random generator = new Random();
                    int n = 10000;
                    n = generator.nextInt(n);
                    String fname = "Image-"+ n +".jpg";
                    File file = new File (myDir, fname);

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

                        FileOutputStream out = new FileOutputStream(file);
                        bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                        out.flush();
                        out.close();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
            }
        });

        final ScrollView scrollview = (ScrollView) findViewById(R.id.scroll);
        scrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener(){

            @Override
            public void onScrollChanged() {
                if (scrollview != null) {
                    if (scrollview.getChildAt(0).getBottom() <= (scrollview.getHeight() + scrollview.getScrollY())) {
                           View v1 = L1.getRootView();
                            v1.setDrawingCacheEnabled(true);
                            Bitmap bm = v1.getDrawingCache();
                            BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                            image = (ImageView) findViewById(R.id.ImageView02);
                            image.setBackgroundDrawable(bitmapDrawable);

                            Log.e("top-->", String.valueOf(bitmapDrawable));


                            bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);

                            //String path = Environment.getExternalStorageDirectory().toString();
                        File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
                            myDir.mkdirs();
                            Random generator = new Random();
                            int n = 10000;
                            n = generator.nextInt(n);
                            String fname = "Image-"+ n +".jpg";
                            File file = new File (myDir, fname);

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

                                FileOutputStream out = new FileOutputStream(file);
                                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                                out.flush();
                                out.close();
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }

                    } else {

                        View v1 = L1.getRootView();
                        v1.setDrawingCacheEnabled(true);
                        Bitmap bm = v1.getDrawingCache();
                        BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                        image = (ImageView) findViewById(R.id.ImageView01);
                        image.setBackgroundDrawable(bitmapDrawable);

                        Log.e("bottom-->", String.valueOf(bitmapDrawable));

                        bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);

                       // String path = Environment.getExternalStorageDirectory().toString();
                        File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
                        myDir.mkdirs();
                        Random generator = new Random();
                        int n = 10000;
                        n = generator.nextInt(n);
                        String fname = "Image-"+ n +".jpg";
                        File file = new File (myDir, fname);

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

                            FileOutputStream out = new FileOutputStream(file);
                            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                            out.flush();
                            out.close();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }



                    }
                }

            }
        });
    }
}

图片无法保存在SD卡中。我犯了什么错误?我无法理解问题是什么或如何在SD卡上保存图像?

3 个答案:

答案 0 :(得分:0)

我使用此方法捕获屏幕。首先,添加适当的权限以保存文件:

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

这是代码(在Activity中运行):

private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

try {
    // image naming and path  to include sd card  appending name you choose for file
    String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

    // create bitmap screen capture
    View v1 = getWindow().getDecorView().getRootView();
    v1.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);

    File imageFile = new File(mPath);

    FileOutputStream outputStream = new FileOutputStream(imageFile);
    int quality = 100;
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
    outputStream.flush();
    outputStream.close();

    openScreenshot(imageFile);
} catch (Throwable e) {
    // Several error may come out with file handling or OOM
    e.printStackTrace();
}
 }

这就是你打开最近生成的图像的方法:

private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}

答案 1 :(得分:0)

试试这个, 在编写文件之前,您必须检查marshmallow的权限

   public static final int REQUEST_STORAGE = 101;
   if (Build.VERSION.SDK_INT >= 23) {
    String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
    if (!hasPermissions(mContext, PERMISSIONS)) {
        ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE);
    } else {
     writeFile()
    }
    }

     /*check permissions  for marshmallow*/
    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

     /*get Permissions Result*/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("TAG", "PERMISSION_GRANTED");
                    writeFile();
                } else {
                    Toast.makeText(mContext, "The app was not allowed to write to your storage", Toast.LENGTH_LONG).show();
                }
            }

        }
    }


    public void writeFile()
    {
                View v1 = L1.getRootView();
                v1.setDrawingCacheEnabled(true);
                Bitmap bm = v1.getDrawingCache();
                BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
                image = (ImageView) findViewById(R.id.ImageView02);
                image.setBackgroundDrawable(bitmapDrawable);

                Log.e("top-->", String.valueOf(bitmapDrawable));



                bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);

                //String path = Environment.getExternalStorageDirectory().toString();
                File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
                myDir.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-"+ n +".jpg";
                File file = new File (myDir, fname);

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

                    FileOutputStream out = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
    }

答案 2 :(得分:0)

final String root = Environment.getExternalStorageState().toString();
File myDir=new File(root + "/saved_images/" );

国家不存储。改为:

File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images" );

并根据评论中的说明调整mkdirs的代码。

if (!myDir.exists())
  {
   if (!myDir.mkdirs())
       {
        Toast.makeText(this, "Sorry could not create directory:\n" + myDir.getAbsolutePath(), Toast.LENGTH_LONG).show();
        return;
        }
    }

您抱怨该文件未创建,但它从目录开始。

你永远不会回答我关于Androud版本的问题。但是对于6.0及更高版本,您还应该询问用户是否有运行时权限。添加该代码。

或者,作为快速解决方案,请转到应用的Android设置,然后将存储切换按钮切换为开启。