x1uan x1uan - 1 month ago 10
Android Question

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!

Answer

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