简体   繁体   中英

How Android Saving Files?

I need to save some files into my Android phone. 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:

<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.

This is really confusing for me, could someone explain it to me how the Android file system works? Thank you all!

To save image on 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

  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.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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