简体   繁体   English

Android如何保存文件?

[英]How Android Saving Files?

I need to save some files into my Android phone. 我需要将一些文件保存到我的Android手机中。 So I used something like: 所以我用了类似的东西:

FileOutputStream os = null;
 try{
     os = new FileOutputStream("/root/sdcard/DCIM/1.jpg");
     os.write(bytes);
     os.close();
 }catch(FileNotFoundException e){}

When I do this, it would say something like 当我这样做时,它会说类似

java.io.FileNotFoundException: /root/sdcard/DCIM/1.jpg (Permission denied)

Btw, I already requestd permission in AndroidManifest.xml using something like: 顺便说一句,我已经使用以下方法在AndroidManifest.xml中请求了权限:

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

I also tried 我也试过

getFilesDir().getAbsolutePath();

And it actually refers to 它实际上是指

/data/user/0/come.package.xxx/files

Which I have no idea where this path is because I could not find it on my phone. 我不知道该路径在哪里,因为我无法在手机上找到它。 When I use ASUS File Manager, I see the path is /root/sdcard/..., but I don't even have a sdcard in my phone, I have been using iPhone for many years now, so I don't know how the Android file system works now. 当我使用ASUS File Manager时,我看到的路径是/ root / sdcard / ...,但是我的手机中甚至没有sdcard,我已经使用iPhone多年了,所以我不知道Android文件系统现在如何工作。

This is really confusing for me, could someone explain it to me how the Android file system works? 这真的让我感到困惑,有人可以向我解释一下Android文件系统的工作原理吗? Thank you all! 谢谢你们!

To save image on Android: 在Android上保存图像:

private String saveToInternalStorage(String name, Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(context);
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir(IMAGE_TAG, Context.MODE_PRIVATE);
        // Create imageDir
        File mypath = new File(directory, name + ".jpg");

        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return directory.getAbsolutePath();
    }

To load image: 加载图像:

public void loadImage(ImageView imageView) {
        // get path
        ContextWrapper cw = new ContextWrapper(context);
        File directory = cw.getDir(IMAGE_TAG, Context.MODE_PRIVATE);
        String path = directory.getAbsolutePath();

        // load image
        try {
            File f = new File(path, name + ".jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            imageView.setImageBitmap(b);
            imageView.setVisibility(View.VISIBLE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d("Image", "Image file not found.");    
        }
}

if you are using android 6.0 Marsh or higher android version u need to give run time permission to access.try below code 如果您使用的是Android 6.0 Marsh或更高版本的Android,则需要授予运行时访问access.try的权限,代码如下

  if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            camera.setEnabled(false);
           ActivityCompat.requestPermissions(getActivity(), new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
       }
 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                //permission will get success here
                //do what you want
            }
            else {
                //Permission not granted
                Toast.makeText(getActivity(),"You need to grant camera permission to use camera",Toast.LENGTH_LONG).show();
            }
        }
    }

if your are using marshmallow or latest version of android so you need to provide permission at run time, on your buttom click than you need to call your code for saving file into sd card. 如果您使用的是棉花糖或最新版本的android,则需要在运行时提供权限,然后单击按钮即可调用将代码保存到SD卡的代码。

after than do like this, 比做完之后

public void onClick(View v) {
    // write on SD card file data in the text box
    try {
        File myFile = new File("/sdcard/mysdfile.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = 
                                new OutputStreamWriter(fOut);
        myOutWriter.append(txtData.getText());
        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(),
                "Done writing SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM