Android Saving File to External Storage

Android saving file to external storage

Use this function to save your bitmap in SD card

private void SaveImage(Bitmap finalBitmap) {

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
if (!myDir.exists()) {
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);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();

} catch (Exception e) {
e.printStackTrace();
}
}

and add this in manifest

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

EDIT: By using this line you will be able to see saved images in the gallery view.

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));

look at this link also http://rajareddypolam.wordpress.com/?p=3&preview=true

Saving files in Android 11 to external storage(SDK 30)

You can save files to the public directories on external storage.

Like Documents, Download, DCIM, Pictures and so on.

In the usual way like before version 10.

Saving Files in Android - For Beginners (Internal / External Storage)

The terms "Internal Storage" and "External Storage" might be confusing at first, because Google's intentions are different from what we would expect & know from our day-to-day use of language: "External" doesn't necessarily mean the "SD Card". This guy made a great article about the terminology confusion

According to your intentions, you'd want to be working with the External Storage concept. The differences are well explained in the Documentation, but I'll shortly brief them to you here.

At the end I'll provide you an example, but first lets know the basics:

Internal Storage

  • Files are accessible by only your app
  • Files are removed when your app is uninstalled
  • Files are always available (meaning they files will never be saved on a removable memory)

External Storage

  • Files are fully readable by other apps (including any variant of File Manager app, in your case)
  • Files aren't necessarily removed when your app is uninstalled - explained later
  • Files availability isn't guaranteed (can be deleted by other apps / removable memory)

So now that we know you need External Storage, there are several things needed to be done before starting:

  • Require Permissions (read/write) inside your Manifest.xml file, depending on your needs:
    <manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>

Each permission stands by its own, meaning you don't need to have both if, for example, you only wish to read files instead of writing them

  • Verify that storage is available - this is done on runtime, and is well explained inside the documentation. We need to make sure the storage is mounted into the device / its state is not problematic somehow in a way that would cause a failure of read/write requests.

Example Time!

In the given method, we will save a text file inside the root directory.

Credits to this article

public void writeFileExternalStorage() {

//Text of the Document
String textToWrite = "bla bla bla";

//Checking the availability state of the External Storage.
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {

//If it isn't mounted - we can't write into it.
return;
}

//Create a new file that points to the root directory, with the given name:
File file = new File(getExternalFilesDir(null), filenameExternal);

//This point and below is responsible for the write operation
FileOutputStream outputStream = null;
try {
file.createNewFile();
//second argument of FileOutputStream constructor indicates whether
//to append or create new file if one exists
outputStream = new FileOutputStream(file, true);

outputStream.write(textToWrite.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

I'd like to answer specifically to some of your questions:

do I need to create those folders in the android studio as adding folders? or do I need to create it from code?

Definitely not via the Android Studio. These are your projects folder, containing your code. The way to do it is mentioned above.

I couldn't find the folder with my app name and inside it my Databases and Images folders... What am I doing wrong?

Probably saved your files as Internal Storage ones / saved them as project folders as you mentioned earlier - and those wouldn't (and shouldn't) show up.


Useful things to know

There are 2 types of directories: public and private.

Private

  • Not accessible by the Media Store
  • Files are removed when app is uninstalled
  • Retrieved by getExternalFilesDir(...) method

Example: the WhatsApp directory (in my phone) is located right at the root level. Calling it would be: getExternalFilesDir("WhatsApp/...")

Public (Downloads/Movies/Images libraries)

  • Files are scanned by the MediaStore
  • Retrieved by Environment.getExternalStoragePublicDirectory(...) method

Example: getting the Documents folder would look like: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)

How to save Document file in external storage after android API LEVEL28 With Android SAF(Storage Access Framework))

EDIT :

Well well well, I'm still trying to add anytype of file in the "download" directory.
Personnaly, I'm trying to copy a file from my assetFolder and paste it to the "Download" folder. I haven't succeeded yet.
However, I can currently CREATE anytype of file in that folder, it's working with the method below. I hope this can help you.

Here is my code :

    public void saveFileToPhone(InputStream inputStream, String filename) {
OutputStream outputStream;
Context myContext = requireContext();
try {
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.Q){
ContentResolver contentResolver = requireContext().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Downloads.DISPLAY_NAME,filename);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri fileUri = contentResolver.insert(collection, contentValues);
outputStream = contentResolver.openOutputStream(Objects.requireNonNull(fileUri));
Objects.requireNonNull(outputStream);

}
}catch (FileNotFoundException e) {

e.printStackTrace();
}
}

how to save file to external storage, currently it creates document but it size is 0B

first, start activity for result

Intent i = new Intent(Intent.ACTION_CREATE_DOCUMENT);
i.setType("application/x-sqlite3");
startActivityForResult(i, BACKUP_CODE);

after this it will create file with size of 0 B so we have to write backup in onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == BACKUP_CODE) {
try {
assert data != null;
FileOutputStream stream = (FileOutputStream) getContentResolver().openOutputStream(data.getData());
Files.copy(Paths.get(getDatabasePath(DATABASE).toPath()), stream);
Toast.makeText(this, "done", Toast.LENGTH_SHORT).show();
stream.close(); ///very important
} catch (Exception e) {
Toast.makeText(this, "Error occurred in backup", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}

it'll successfully creates backup. It worked for me.



Related Topics



Leave a reply



Submit