Android save files java

Saving data to a file in your Android application

This is the second post in my series about storage in Android applications. The other post is available here :

This post is about saving to a file from an Android application, which is the easiest way to store data. There are many situations where you may need to save a file : you may want to use an existing file format to create files that can be opened by the user in another application or the data is simple enough that it can be represented by a text file or a format like XML or YAML. For complex data a database may be a better option, since accessing and parsing a large file can be slow and there are no integrity checks unless you code them by hand. On the other hand, there is less overhead and it easier to work with files than debugging with the data in a database. Depending on how the user will interact (or not) with your files, you will need to decide first which kind of storage to use.

Internal storage

Each application has its own private internal storage to save files. This is the kind of storage to use if the user shouldn’t be able to modify the file from outside your application, and if other application shouldn’t be able to access those files. Since the internal storage is private to your application, the files will be deleted if your application is uninstalled. The internal storage is also where your application is installed by default, so your files will always be available. On some older or cheaper devices the internal storage is quite limited, so you need to be careful about the size of the data you save if you need to support those devices.

Читайте также:  Progress bar in console python

You should never hardcode the path to the storage directories, since the directory may changes depending on the version of the Android OS used. Also, Android 4.4 introduces the concept of multiple users : in that case, the internal and external storage depend on the user logged in and the files of the other users will be invisible. Here are some of the methods used to get the paths to the internal storage:

  • android.content.Context.getFilesDir(): returns a java.io.File object representing the root directory of the internal storage for your application from the current context.
  • android.content.Context.getDir(String name, Context.MODE_PRIVATE):returns a java.io.File object representing the directory name in the internal storage, creating the directory if it does not exists. The second parameter can also be used to set the directory to MODE_WORLD_READABLE or MODE_WORLD_WRITABLE so it is visible by all the other applications, but this is is risky security-wise and was deprecated in API level 17 (Android 4.2).
  • android.content.Context.getCacheDir(): returns a java.io.File object representing the internal cache directory for the application. This is mean for small files (the documentation suggests no more that 1MB total) that can be deleted at any time when the system needs more storage. There is no guarantee that the cache will be cleared, so you must also clear those files manually when they are not needed anymore.

As you can see, the files are represented by the File object from the java.io namepace: there is no file object specific to the Android SDK and the standard Java APIs for reading and writing files are used. Also, there is no specific application permission to set in the Android manifest to use the internal storage since it is already private to the application.

External storage

In addition of the internal storage, there is an external storage space shared by all the applications that is kept when your application is uninstalled. This is the storage that is shown when using a file explorer application and when the device is plugged in your computer. It may be implemented as a SD card that can be removed or as a partition of the built-in storage in the device, so your application should be able to work even if the card is removed or changed. To check the current state of the external storage, you can call the getExternalStorageState() method.

Читайте также:  Открыть папку через html

On device with many users (starting with Android 4.4), the external storage is specific to the current user and files for other users can’t be accessed. Also, there may be more than one external storage if the device has a built-in external storage which is a partition on the internal memory and a SD card: in that case, the built-in storage is the primary external storage. Reading files from the external storage requires the READ_EXTERNAL_STORAGE permission and writing or reading files requires the WRITE_EXTERNAL_STORAGE permission.

Here are the methods you should use to call to get the directories of the primary external storage:

  • android.os.Environment.getExternalStorageDirectory(): returns a java.io.File object representing the root directory of the primary external storage of the device that is shared by all applications.
  • android.os.Environment.getExternalStoragePublicDirectory(): returns a java.io.File object representing a public directory for files of a particular type on the primary external storage of the device. For example, you can get the path to the public music directory by calling Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) or the public pictures directory by calling Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).
  • android.content.Context.getExternalFilesDir(): returns a java.io.File representing the root directory of the primary external storage specific to your application, which is under the directory returned by getExternalStorageDirectory(). Unlike the other directories of the external storage, the files you store in that folder will be deleted when your application is uninstalled. So, if you need to store files that are only needed by your application you should use this folder. Also, there is no specific permission needed for the application to read or write to its own external storage starting with Android 4.4, but with older versions your application needs the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission.
  • android.content.Context.getExternalFilesDirs(): returns an array of java.io.File representing the root directories of all the external storage directories that can be used by your application with the primary external storage as the first directory in the array. All those directories works the same as the primary storage returned by the getExternalFilesDir() method. If the device has a built-in storage as the primary external storage and a SD card as a secondary external storage, this is the only way to get the path to the SD card. This method was introduced in Android 4.4, before that it was impossible to get the path to the secondary storage.
  • android.content.Context.getExternalCacheDir(): returns a java.io.File object representing the cache of the application on the primary external storage. This cache is not visible to the user and is deleted when the application is uninstalled. There is no mechanism in the Android SDK to delete files in the cache directory, so you need to manage your cache to keep it to a reasonable maximum size. Starting with Android 4.4, the application does not need permission to access its own cache, but with older versions your application needs the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission.
Читайте также:  Python value in between

Example code to save to a file

To save a file, you need to get the path to the storage you want to use which is used the same way regardless of the type of storage used since all the methods returns a java.io.File object representing the directory to use. Here is an example of using the external storage to save a text file from an Activity :

try < // Creates a file in the primary external storage space of the // current application. // If the file does not exists, it is created. File testFile = new File(this.getExternalFilesDir(null), "TestFile.txt"); if (!testFile.exists()) testFile.createNewFile(); // Adds a line to the file BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true /*append*/)); writer.write("This is a test file."); writer.close(); // Refresh the data so it can seen when the device is plugged in a // computer. You may have to unplug and replug the device to see the // latest changes. This is not necessary if the user should not modify // the files. MediaScannerConnection.scanFile(this, new String[], null, null); > catch (IOException e)

And here is an example of how to read from the file you just wrote :

String textFromFile = ""; // Gets the file from the primary external storage space of the // current application. File testFile = new File(this.getExternalFilesDir(null), "TestFile.txt"); if (testFile != null) < StringBuilder stringBuilder = new StringBuilder(); // Reads the data from the file BufferedReader reader = null; try < reader = new BufferedReader(new FileReader(testFile)); String line; while ((line = reader.readLine()) != null) < textFromFile += line.toString(); textFromFile += "\n"; >reader.close(); > catch (Exception e) < Log.e("ReadWriteFile", "Unable to read the TestFile.txt file."); >>

Источник

Android External Storage — Read, Write, Save File

Android External Storage - Read, Write, Save File

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the 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

  • 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

android external storage

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.

if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) < saveButton.setEnabled(false); >private static boolean isExternalStorageReadOnly() < String extStorageState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) < return true; >return false; > private static boolean isExternalStorageAvailable() < String extStorageState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(extStorageState)) < return true; >return false; > 

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:

package com.journaldev.externalstorage; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import android.os.Bundle; import android.app.Activity; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity < EditText inputText; TextView response; Button saveButton,readButton; private String filename = "SampleFile.txt"; private String filepath = "MyFileStorage"; File myExternalFile; String myData = ""; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); inputText = (EditText) findViewById(R.id.myInputText); response = (TextView) findViewById(R.id.response); saveButton = (Button) findViewById(R.id.saveExternalStorage); saveButton.setOnClickListener(new OnClickListener() < @Override public void onClick(View v) < try < FileOutputStream fos = new FileOutputStream(myExternalFile); fos.write(inputText.getText().toString().getBytes()); fos.close(); >catch (IOException e) < e.printStackTrace(); >inputText.setText(""); response.setText("SampleFile.txt saved to External Storage. "); > >); readButton = (Button) findViewById(R.id.getExternalStorage); readButton.setOnClickListener(new OnClickListener() < @Override public void onClick(View v) < try < FileInputStream fis = new FileInputStream(myExternalFile); DataInputStream in = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) < myData = myData + strLine; >in.close(); > catch (IOException e) < e.printStackTrace(); >inputText.setText(myData); response.setText("SampleFile.txt data retrieved from Internal Storage. "); > >); if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) < saveButton.setEnabled(false); >else < myExternalFile = new File(getExternalFilesDir(filepath), filename); >> private static boolean isExternalStorageReadOnly() < String extStorageState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) < return true; >return false; > private static boolean isExternalStorageAvailable() < String extStorageState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(extStorageState)) < return true; >return false; > > 
  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.

android external storage config, android save file to external storage

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

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