Запись данных в файл java android 5. Чтение и запись файлов

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

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). Many devices now divide the permanent storage space into separate "internal" and "external" partitions. So even without a removable storage medium, these two storage spaces always exist, and the API behavior is the same regardless of whether the external storage is removable.

Because the external storage might be removable, there are some differences between these two options as follows.

Tip: Although apps are installed onto the internal storage by default, you can allow your app to be installed on external storage by specifying the attribute in your manifest. 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 .

Save a file on internal storage

Your app"s internal storage directory is specified by your app"s package name in a special location of the Android file system that can be accessed with the following APIs.

On Android 6.0 (API level 23) and lower, other apps can read your internal files if you set the file mode to be world readable. However, the other app must 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 for your files on the internal storage, they are never accessible to other apps.

Write a cache file

If you instead need to cache some files, you should use . For example, the following method extracts the file name from a and creates a file with that name in your app"s internal cache directory:

Kotlin

private fun getTempFile(context: Context, url: String): File? = Uri.parse(url)?.lastPathSegment?.let { filename -> File.createTempFile(filename, null, context.cacheDir) }

Java

private File getTempFile(Context context, String url) { File file; try { String fileName = Uri.parse(url).getLastPathSegment(); file = File.createTempFile(fileName, null, context.getCacheDir()); } catch (IOException e) { // Error while creating file } return file; }

Tip: If you need to package a file in your app that is accessible at install time, save the file in your project"s res/raw/ directory. You can open these files with , passing the R.raw. filename resource ID. This method returns an that you can use to read the file. You cannot write to the original file.

Open a directory

You can open a directory on the internal file system with the following methods:

Returns a representing the directory on the file system that"s uniquely associated with your app. Creates a new directory (or opens an existing directory) within your app"s unique file system directory. This new directory appears inside the directory provided by . Returns a representing the cache directory on the file system that"s uniquely associated with your app. This directory is meant for temporary files, and it should be cleaned up regularly. The system may delete files there if it runs low on disk space, so make sure you check for the existence of your cache files before reading them.

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

Kotlin

val directory = context.filesDir val file = File(directory, filename)

Java

File directory = context.getFilesDir(); File file = new File(directory, filename);

Save a file on external storage

Using the external storage is great for files that you want to share with other apps or allow the user to access with a computer.

Request external storage permissions

To write to the public external storage, you must request the permission in your :

... ...

Beginning with Android 4.4 (API level 19), reading or writing files in your app"s private external storage directory-accessed using -does not require the or permissions. So if your app supports Android 4.3 (API level 18) and lower, and you want to access only the private external storage directory, you should declare that the permission be requested only on the lower versions of Android by adding the attribute:

...

Verify that external storage is available

Because the external storage might 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 . If the returned state is , then you can read and write your files. If it"s , you can only read the files.

For example, the following methods are useful to determine the storage availability:

Kotlin

/* Checks if external storage is available for read and write */ fun isExternalStorageWritable(): Boolean { return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED } /* Checks if external storage is available to at least read */ fun isExternalStorageReadable(): Boolean { return Environment.getExternalStorageState() in setOf(Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY) }

Java

/* Checks if external storage is available for read and write */ public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } /* Checks if external storage is available to at least read */ public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; }

Save to a public directory

If you want to save public files on the external storage, use the method to get a 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 or . For example:

Kotlin

fun getPublicAlbumStorageDir(albumName: String): File? { // Get the directory for the user"s public pictures directory. val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName) if (!file?.mkdirs()) { Log.e(LOG_TAG, "Directory not created") } return file }

Java

public File getPublicAlbumStorageDir(String albumName) { // Get the directory for the user"s public pictures directory. File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) { Log.e(LOG_TAG, "Directory not created"); } return file; }

If you want to hide your files from the Media Scanner, include an empty file named .nomedia in your external files directory (note the dot prefix in the filename). This prevents media scanner from reading your media files and providing them to other apps through the content provider.

Save to a private directory

If you want to save files on external storage that are private to your app and not accessible by the content provider, you can acquire a directory that"s used by only your app by calling 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.

Caution: Files on external storage are not always accessible , because users can mount the external storage to a computer for use as a storage device. So if you need to store files that are critical to your app"s functionality, you should instead store them on .

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

Kotlin

fun getPrivateAlbumStorageDir(context: Context, albumName: String): File? { // Get the directory for the app"s private pictures directory. val file = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), albumName) if (!file?.mkdirs()) { Log.e(LOG_TAG, "Directory not created") } return file }

Java

public File getPrivateAlbumStorageDir(Context context, String albumName) { // Get the directory for the app"s private pictures directory. File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) { Log.e(LOG_TAG, "Directory not created"); } return file; }

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

Kotlin

myFile.delete()

Java

myFile.delete();

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

Kotlin

myContext.deleteFile(fileName)

Java

myContext.deleteFile(fileName);

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

  • All files you saved on internal storage.
  • All files you saved external storage using .

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

Read and write operations to file are standard functionality of any applications that are logging the events, work with files, up to the transfer of data over the network. In this article, we consider methods of recording information in the files, and read from a file recorded line.

Project structure

Esthetic changes to the standard buttons or ListView will not be made in this lesson, since we work with what is hidden from the eyes of the user, namely, to work with files.

The entire structure of the project respectively is at this time only one class: MainActivity

Also, the project contains the following resource files:

  1. activity_main.xml
  2. strings.xml
  3. styles.xml - in the file does not have any changes relating to a project.

In addition, changes in the AndroidManifest.xml file. The file you need to add the following two lines. This permits the application - perform read and write operations to an external storage (ie SD Card phone) in modern smartphones based on the Android operating system in the majority of cases, the recording of information is carried out in an external drive, though typical user finds the drive internal, because it is built, but in terms of operating systems, this drive (ie SD Card) is an external drive. This article will not be considered an option to work with a true inner drive.

...

Formation apps layout

activity_main.xml

Layout main Activiti, which will be the work of our application. This markup is present only two buttons (Button) and a text box (TextView), in which we will display information stored in the file.