Android save file example

Saving Files

This lesson teaches you to

You should also read

Android uses a file system that’s similar to disk-based file systems on other platforms. This lesson describes how to work with the Android file system to read and write files with the File APIs.

A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it’s good for image files or anything exchanged over a network.

This lesson shows how to perform basic file-related tasks in your app. The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io .

Choose Internal or External Storage

All Android devices have two file storage areas: «internal» and «external» storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into «internal» and «external» partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.

  • It’s always available.
  • Files saved here are accessible by only your app by default.
  • When the user uninstalls your app, the system removes all your app’s files from internal storage.

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

  • It’s not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
  • It’s world-readable, so files saved here may be read outside of your control.
  • When the user uninstalls your app, the system removes your app’s files from here only if you save them in the directory from getExternalFilesDir() .

External storage is the best place for files that don’t require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.

Tip: Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. Users appreciate this option when the APK size is very large and they have an external storage space that’s larger than the internal storage. For more information, see App Install Location.

Obtain Permissions for External Storage

To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.

You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.

Save a File on Internal Storage

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir() Returns a File representing an internal directory for your app. getCacheDir() Returns a File representing an internal directory for your app’s temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it may delete your cache files without warning.

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here’s how to write some text to a file:

Or, if you need to cache some files, you should instead use createTempFile() . For example, the following method extracts the file name from a URL and creates a file with that name in your app’s internal cache directory:

Note: Your app’s internal storage directory is specified by your app’s package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to know your app package name and file names. Other apps cannot browse your internal directories and do not have read or write access unless you explicitly set the files to be readable or writable. So as long as you use MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.

Читайте также:  Самый дорогой плеер для андроид

Save a File on External Storage

Because the external storage may be unavailable—such as when the user has mounted the storage to a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by calling getExternalStorageState() . If the returned state is equal to MEDIA_MOUNTED , then you can read and write your files. For example, the following methods are useful to determine the storage availability:

Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:

Public files Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.

For example, photos captured by your app or other downloaded files.

Private files Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don’t provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app’s external private directory.

For example, additional resources downloaded by your app or temporary media files.

If you want to save public files on the external storage, use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES . For example:

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you’d like. Each directory created this way is added to a parent directory that encapsulates all your app’s external storage files, which the system deletes when the user uninstalls your app.

For example, here’s a method you can use to create a directory for an individual photo album:

If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null . This returns the root directory for your app’s private directory on the external storage.

Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you’re saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory() .

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files that are private to your app, it’s important that you use directory names provided by API constants like DIRECTORY_PICTURES . These directory names ensure that the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.

Query Free Space

If you know ahead of time how much data you’re saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace() . These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.

However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace() . If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it’s probably safe to proceed. Otherwise, you probably shouldn’t write to storage.

Note: You aren’t required to check the amount of available space before you save your file. You can instead try writing the file right away, then catch an IOException if one occurs. You may need to do this if you don’t know exactly how much space you need. For example, if you change the file’s encoding before you save it by converting a PNG image to JPEG, you won’t know the file’s size beforehand.

Delete a File

You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.

If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile() :

Note: When the user uninstalls your app, the Android system deletes the following:

  • All files you saved on internal storage
  • All files you saved on external storage using getExternalFilesDir() .

However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

Читайте также:  What is an activity in android java

Источник

Android save file example

This post shows how to translate text between languages with an example.

Identify Language of Text with Firebase API Android Example

This post explains how to build a feature in android app that identifies the language of given text.

Organize Photos by Content Android Example

This post explains how to create in android a feature that lets user organize photos by its content.

Android Barcode Scanning Example

This post explains how to develop barcode scanning feature in android app using Firebase machine learning kit which provides barcode scanning API.

Extracting Text from Images Android

To recognize and extract text from images, Firebase ML kit can be used. Firebase ML kit offers machine learning features and is based on Google ML technologies.

Google Places SDK for Android Tutorial

Using Google places SDK for Android, current places, place details, nearby places and photos associated with a place can be displayed in apps and place search capability can be developed.

Android Widget Example

One of the excellent features of Android is that app’s information and features can be displayed as mini apps on home screens. These mini apps are called widgets.

Android MotionLayout Examples

MotionLayout is a subclass of ConstraintLayout. It allows you to animate property changes of UI elements which are part of a layout.

Android Fragments Transition Animation Example

To minimize the number of un-installations of your app, you need to build it in such way that it performs well, works on all devices and is user friendly.

Model View ViewModel MVVM Android Example

Model View ViewModel (MVVM) is an architectural pattern applied in applications to separate user interface code from data and business logic.

Android Model View Presenter MVP Pattern Example

If you want to build android apps which can be tested and modified easily, you need to implement user interface architectural pattern in your app.

Android Kotlin ListView Example

It is very common in most of the applications that a list of data items is displayed in UI. In android applications, list of data items can be shown to users using ListView.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

Android External Storage – Read, Write, Save File

Android Tutorial

Android external storage can be used to write and save data, read configuration files etc. This article is continuation of the Android Internal Storage tutorial in the series of tutorials on structured data storage in android.

Android External Storage

External storage such as SD card can also store application data, there’s no security enforced upon files you save to the external storage.
In general there are two types of External Storage:

  • Primary External Storage: In built shared storage which is “accessible by the user by plugging in a USB cable and mounting it as a drive on a host computer”. Example: When we say Nexus 5 32 GB.
  • Secondary External Storage: Removable storage. Example: SD Card

All applications can read and write files placed on the external storage and the user can remove them. We need to check if the SD card is available and if we can write to it. Once we’ve checked that the external storage is available only then we can write to it else the save button would be disabled.

Android External Storage Example Project Structure

Firstly, we need to make sure that the application has permission to read and write data to the users SD card, so lets open up the AndroidManifest.xml and add the following permissions:

Also, external storage may be tied up by the user having mounted it as a USB storage device. So we need to check if the external storage is available and is not read only.

getExternalStorageState() is a static method of Environment to determine if external storage is presently available or not. As you can see if the condition is false we’ve disabled the save button.

Android External Storage Example Code

The activity_main.xml layout is defined as follows:

Here apart from the save and read from external storage buttons we display the response of saving/reading to/from an external storage in a textview unlike in the previous tutorial where android toast was displayed.

The MainActivity.java class is given below:

  1. Environment.getExternalStorageState(): returns path to internal SD mount point like “/mnt/sdcard”
  2. getExternalFilesDir(): It returns the path to files folder inside Android/data/data/application_package/ on the SD card. It is used to store any required files for your app (like images downloaded from web or cache files). Once the app is uninstalled, any data stored in this folder is gone too.

Also if the external storage is not available we disable the save button using the if condition that was discussed earlier in this tutorial.

Below is our application running in android emulator, where we are writing data to file and then reading it.

Note: Make sure your Android Emulator is configured such that it has a SD card as shown in the image dialog from AVD below. Go to Tools->Android->Android Virtual Device, edit configurations->Show Advance Settings.

This brings an end to this tutorial. We’ll discuss storage using Shared Preferences in the next tutorial. You can download the final Android External Storage Project from the below link.

Читайте также:  Можно ли обновить свой андроид до последней версии

Android Internal Storage Example Tutorial

Android Shared Preferences Example Tutorial

He loves learning new stuff in Android and iOS. Shoot him queries.

Comments

Hey I want to make a folder in primary external storage like storage/my folder not in the app data. Can you please suggest me any way to do it.

edit text and button
when i write something in edit text and click on button of save ,then open external memory storage .ask to user where you want to save the file .i am trying this but can’t find please help me.

Dont Save pdf file Internal Storage Android studio sdk 30.
My Code
String myFilePath = Environment.getExternalStorageDirectory().getPath() + “/REQUISITION.pdf”;
File file = new File(myFilePath);
try <
myPdfDocument.writeTo(new FileOutputStream(file));
Toast.makeText(Createidepdf.this, “PDF File Create”, Toast.LENGTH_LONG).show();

> catch (IOException e) <
e.printStackTrace();
>

I am using Android 8.1.
I have connected a secondary storage. We creates database for secondary storage in /data/data/my-package_name/databases/external.db

When I am checking manually from the emulator database is exists and inside the database content is also present.

When I am checking whether database is present or not through below code snippet

File database = new File(“/data/data/my-package_name/database/external.db”);
boolean result = database.exists();

But the result is always false.

1) Path is proper.
2) Given WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permission
3) Even tried by giving path permission in AndroidManifest file.
4) getAbsolutePath() return proper file path but database.getAbsolutePath().exists() is returning always false.

If any one have idea please suggest me?

java.io.FileNotFoundException: /document/primary:WhatsApp/Media/WhatsApp Documents/UploadContest.xlsx (No such file or directory)

omg this is so coool1. exactly what i wanted!! compact code

File is saved to Internal Storage not SD card bro!

If i connected pen drive to device then how could i get path in my app to store video file in pen drive
also if i get path of pen drive then how to create folder or save file in pen drive.
If you have solution then please tell me

Yes i have a solution

can i know where my file is saved.

check in logcat there show your file path

I want to save data in sqlite for saving android app data offline and sync the saved data when online. please help.

Nice, but this example only use primary external storage. What about Secondary External Storage as you comment at the top of this post?

please post mediaplayer example.

String mediaPath = “/sdcard/Omnamashivaya.mp3″;
Uri uriPath = Uri.parse(mediaPath);

MediaPlayer player = new MediaPlayer();
try <
player.setDataSource(getApplicationContext(),uriPath);
player.prepare();
player.start();

Toast.makeText(getApplicationContext(),”Start to play”,Toast.LENGTH_LONG).show();

> catch (IOException e) <
e.printStackTrace();
>

i got below exception

W/MediaPlayer: Couldn’t open /sdcard/Omnamashivaya.mp3: java.io.FileNotFoundException: No content provider: /sdcard/Omnamashivaya.mp3
W/System.err: java.io.FileNotFoundException: /sdcard/Omnamashivaya.mp3 (Permission denied)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:200)
at java.io.FileInputStream.(FileInputStream.java:150)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1182)
W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1160)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1078)
W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1003)
at com.randy.chennaitourism.MainActivity$override.onCreate(MainActivity.java:35)
at com.randy.chennaitourism.MainActivity$override.access$dispatch(Unknown Source:74)
at com.randy.chennaitourism.MainActivity.onCreate(Unknown Source:15)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4699)
W/System.err: at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1595)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)

hello,
i will recommend you to use exo-player

Ok i got it, e.g. in SDCARD the path android/data/app_name/files/MyFileStorage exists and the folder is empty.

Android SDK built for x86 path android/data/app_name/files/MyFileStorage/SampleFile.txt exists, but what is the difference? :/ And why is the file not on the sdcard? ?
Pla reply

if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) <
return true;
>
return false;

can be rewritten as:

Similarly, any if () < return true; >return false; can be rewritten return ()

Darn, I was afraid the comment box would strip out the left-angle brackets:

if ( ) return false; can be rewritten return ( );

Also forgot to end the statement with a semi-colon, so just as well 🙂

hi dears
im really happy to see these useful tutorial which you put theme in your site
they are really useful and of clear summary
thx alot

Hello,
nice tutorial.
Even I was unable to find file path. I just debugged the app & tried this myExternalFile.getAbsolutePath(); & yipeee I found the correct file path.

For me path is /storage/emulated/0/Android/data/your package name/files/MyFileStorage/SampleFile.txt

Hello, great tutorial but you only covered the primary external storage, what about the secondary one?

thanks for share this 😀

How to export data saved in sqlite to txt file
Thank you !

I also have some doubt….

It is irritating beyond belief that a popup for “FREE eBook” covers up part of the display without even showing a Close button/box. Rest assured I will never buy anything advertised on this web site because of htat.

Layout and layout parameters are not connected to java file in the above code .

hii sir I want make app for English grammar can u tell how can I do it sorry for my poor English

hi anupam ,
i need your help if possible.
i have get image using json web services.
now i need to download this when click download button and image an store in my mobile storage .
how can i perform this task.
YOU CAN REPLY IN MY EMAIL .

Hey your tutorial is awesome and working but i cant find the file, the folder “MyFileStorage” is empty but it’s still working… Can you tell me where i can find the file?

Ok i got it, e.g. in SDCARD the path android/data/app_name/files/MyFileStorage exists and the folder is empty.

Android SDK built for x86 path android/data/app_name/files/MyFileStorage/SampleFile.txt exists, but what is the difference? :/ And why is the file not on the sdcard? 🙂

thank you for your clear explanation and coding
-and you made me nervous, when i received the text toast:
” read from internal storage ” ( its a typo )
ha: its still the external – i am happy.
i like to buy you a drink!

Источник

Оцените статью