Android сохранение в файл. Сохранение файлов. Визуальный редактор XML

Viber OUT 16.03.2019
Viber OUT

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.

В Android можно сохранять файлы непосредственно на мобильном устройстве или на внешнем носителе данных (например, SDкарте ). По умолчанию другие приложения не могут обращаться к этим файлам.

Операции вводавывода в Android аналогичны операциям в стандартных Java-программах. Android реализует потоки с помощью иерархии классов, определенных в пакете java.io . Кроме этих классов в пакете java.io определено множество специализированных классов для операций ввода вывода.

Чтобы прочитать данные из файла, необходимо вызвать метод Context.openFileinput() и передать в качестве параметра имя файла. Метод возвращает стандартный Java-объект Fileinputstream . Например, код для чтения данных из текстового файла может выглядеть так:

InputStream inStream openFiieinput(file.txt); InputStreamReader sr = new InputStreamReader(inStream); // создаем буфер для чтения файла BufferedReader reader new BufferedReader(sr); String str; StringBuffer buffer new StringBuffer(); // читаем данные в буфер while ((str reader.readLine()) null) buffer.append(str + "\n"); inStream.close();

Чтобы записывать в файл, необходимо вызвать метод context.openFileOutput() , передав ему имя файла как параметр. Этот метод возвращает объект FileOutputstream . Вызов этих методов для данного файла из другого приложения не будет работать, обратиться вы можете только к своим файлам. Пример записи строки данных в файл file.txt может быть следующим:

String data; OutputStream outStream = openFileOutput(file.txt, 0); OutputStreamWriter sw new OutputStreamWriter(outStream); sw.write (data); sw.close();

Если имеется статический файл, который надо упаковать с вашим приложением во время компиляции проекта, можно сохранить его в каталоге проекта в папке res/raw/ , а затем открыть его методом Resources.openRawResource() . Он возвращает объект Inputstrearn , который можно использовать для чтения файла. После окончания работы с потоком не забудьте его закрыть, вызвав метод close() .

Обрагиге внимание: Методы openFilelnput() и openFileOutput() не принимают полного пути к файлу (например, path/files/file.txt ), только простые имена файла.

В качестве примера приложения, записывающего и читающего данные из файлов, создадим простейший текстовый редактор с виджетом EditText и меню для открытия файла и сохранения его после редактирования. Создайте в Eclipse новый проект, заполнив поля в окне New Android Project :

  • Project name - ContactEditor;
  • Application name - ReadWrite File Sample;
  • Package name - com.samples.filesrw;
  • Create Activity - EditorActivity.

Код XMLсхемы разметки main.xml, в которой находится единственный элемент EditText:

Файл разметки main.xml

В классе деятельности приложения EditorActivity определим меню из трех пунктов- Open, Save и Exit. Во внутренних методах openFile() и saveFile() реализуем операции по открытию и сохранению файла, приведенные ранее.

Файл класса деятельности EditorActivity.java

Package com.samples.filesrw; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; public class EditorActivity extends Activity { public static final int IDM_OPEN = 101; public static final int IDM_SAVE = 102; public static final int IDM_EXIT = 103; private final static String FILENAME = "file.txt"; private EditText mEdit; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mEdit = (EditText)findViewById(R.id.edit); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, IDM_OPEN, Menu.NONE, "Open") .setIcon(R.drawable.ic_menu_open) .setAlphabeticShortcut("o"); menu.add(Menu.NONE, IDM_SAVE, Menu.NONE, "Save") .setIcon(R.drawable.ic_menu_save) .setAlphabeticShortcut("s"); menu.add(Menu.NONE, IDM_EXIT, Menu.NONE, "Exit") .setIcon(R.drawable.ic_menu_exit) .setAlphabeticShortcut("x"); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case IDM_OPEN: openFile(FILENAME); break; case IDM_SAVE: saveFile(FILENAME); break; case IDM_EXIT: finish(); break; default: return false; } return true; } private void openFile(String fileName) { try { InputStream inStream = openFileInput(FILENAME); if (inStream != null) { InputStreamReader tmp = new InputStreamReader(inStream); BufferedReader reader = new BufferedReader(tmp); String str; StringBuffer buffer = new StringBuffer(); while ((str = reader.readLine()) != null) { buffer.append(str + "\n"); } inStream.close(); mEdit.setText(buffer.toString()); } } catch (Throwable t) { Toast.makeText(getApplicationContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG) .show(); } } private void saveFile(String FileName) { try { OutputStreamWriter outStream = new OutputStreamWriter(openFileOutput(FILENAME, 0)); outStream.write(mEdit.getText().toString()); outStream.close(); } catch (Throwable t) { Toast.makeText(getApplicationContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG) .show(); } } }

Текстовый редактор с возможностью сохранения содержимого в файле

В результате мы получили простую записную книжку, сохраняющую записи сколь угодно долгое время в файле. В качестве упражнения попробуйте усовершенствовать приложение, добавив возможность создания новых файлов, их открытия и сохранения, а также в случае необходимости удаления файлов.

Есть несколько способов разработки приложений для Android, но на сегодняшний день официальный и самый популярный способ - это Android Studio. Это официальная среда разработки, созданная в Google и с помощью нее были разработаны большинство приложений, которыми вы пользуетесь каждый день.

Впервые об Android Studio было объявлено на конференции Google I/O в 2013, а первая версия вышла в 2014 году. До этого большинство приложений разрабатывались в Eclipse, которая представляет из себя более универсальную среду для Java. Android Studio делает разработку приложений намного проще, но она по-прежнему остается сложной. Начинающим пользователям нужно изучить много материалов чтобы уверено ее использовать.

В этой статье мы расскажем как пользоваться Android Studio, поговорим про ее базовые возможности и всем, что нужно чтобы начать работу. И все это максимально просто, чтобы вы смогли сделать свой первый шаг в разработке для Android.

Android Studio предоставляет интерфейс для создания приложений и берет на себя большую часть сложного управления файлами. Вы будете использовать Java для программирования приложений. Несмотря на автоматизацию, большинство возможностей приложения вам все же придется кодировать самому.

В то же время Android Studio дает доступ к Android SDK, это расширение Java, которое позволяет приложениям работать на устройстве и использовать его оборудование. Вы можете запускать программы для тестирования в эмуляторе или сразу на подключенном к компьютеру телефоне. Кроме того, Android Studio выдает различные подсказки во время кодинга, например, подчеркивает ошибки.

Установка Android Studio

Для установки Android Studio в Linux вы можете использовать репозитории PPA или установщик из официального сайта, в Windows доступен полноценный установщик. Мы уже рассматривали в отдельной статье. Настройка android studio перед запуском практически не нужна. Но если вы хотите использовать реальное устройство Android, то в Linux с этим могут возникнуть проблемы. Чтобы их избежать нужно создать файл /etc/udev/rules.d/51-android.rules с таким содержимым:

SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"

Здесь 0bb4 - это идентификатор производителя устройства, вы можете его узнать, выполнив lsusb:

Если не отображается, попробуйте выполнить adb devices. Когда установка будет завершена, вы сможете открыть программу из главного меню:

Как пользоваться Android Studio

1. Создание проекта

Если вы запускаете Android Studio впервые, то перед вами появится окно с возможностью создания нового проекта:

Выберите "Start new Android Project" . В следующем окне введите название приложения и имя домена компании, эта информация будет использоваться для расположения файлов приложения в файловой системе Android.

На следующем этапе создания приложения нужно выбрать платформу. Нас интересует смартфон Android, а версию возьмем 4.2, это одна из самых распространенных:

Осталось только выбрать внешний вид приложения по умолчанию. Шаблон основного окна называется Activity. Приложение может быть вообще без Activity, но лучше все же что-то выбрать.

Также нужно будет ввести некоторые параметры для Activity:

2. Файлы проекта

Интерфейс Android Studio похож на большинство высокоуровневых IDE. Но разработка для Android достаточно сильно отличается от привычного программирования, когда вы набираете программу в одном файле, а потом полностью выполняете. А здесь есть множество файлов ресурсов, которые должны быть сгруппированы между собой.

Программирование в Android Studio выполняется в файлах Java, который имеет такое же имя, как и у Activity. Однако, внешний вид приложения находится в другом файле - это файл xml в котором на языке разметки описаны все элементы приложения. Таким образом, если вы хотите создать кнопку, то вам придется описать ее в xml файле, а чтобы привязать для нее действия - используйте файл Java.

Вот эта строчка кода загружает макет из XML файла:

setContentView (. R.layout activity_main);

Это значит, что мы могли бы использовать один макет для нескольких Activity, а также одна Activity может иметь несколько файлов XML с описанием отображения. Так или иначе, вы можете получить доступ ко всем файлам проекта в левой части окна, а вкладки над рабочей областью позволяют переключаться между теми файлами, которые сейчас открыты.

Кроме того, есть еще папка res, в которой находятся различные ресурсы, такие как изображения. Обратите внимание, что названия всех файлов должны быть в нижнем регистре.

Еще есть папка Values, в которой содержатся XML файлы со значениями различных переменных.

Основная информация о приложении содержится в файле AndroidManifest.xml, здесь описаны полномочия, название приложения, миниатюра, и другое.

Вы можете создать любые файлы, классы и Activity в любой момент, чтобы расширить функциональность приложения. Просто щелкните правой кнопкой мыши по нужному каталогу, а затем выберите "Create" .

3. Визуальный редактор XML

Как вы заметили при редактировании XML файлов внизу страницы появляется две вкладки - "Text" и "Design" . Здесь вы можете не только вручную писать код, но и добавлять нужные элементы в графическом режиме. В окне "Palete" можно выбрать вид виджета, который нужно добавить:

Для добавления его достаточно перетащить на макет приложения. Например, я добавил WebView, Button, Plain Text и Text. С помощью синей рамки вы можете изменять размер элементов, а также изменять их положение.

Но как вы поняли без файлов Java контент XML ничего делать не будет.. Теперь программирование в android studio. Под строками import добавьте:

import android.webkit.WebView;

Затем добавьте эти строки в конец метода onCreate:

WebView mywebview = (WebView) findViewById(R.id.webView);
mywebview.loadUrl("https://сайт");

4. Использование Gradle

В Android Studio все инструменты реализованы просто и красиво. Но некоторые из них более сложные. Один из таких инструментов, которые вы могли заметить - это Gradle. Это инструмент автоматизации сборки, который существенно упрощает превращение всех этих файлов в один готовый APK.

Время от времени вам придется редактировать настройки Gradle, которые находятся в файлах *.gradle, а также если что-то перестанет работать, то вы всегда сможете выбрать в меню "Build" опцию "Clear project" , которая часто помогает.

5. Сборка и отладка

Когда вы будете готовы протестировать приложение, у вас будет два варианта - либо запустить его на реальном устройстве, либо в эмуляторе.

Запустить приложение на устройстве очень просто. Достаточно подключить его по USB и выполнить "Run" , затем "Run App" . Обратите внимание, что в настройках телефона должна быть разрешена отладка по USB и установка из недостоверных источников:



В открывшемся окне вам предстоит выбрать устройство или создать виртуальное. После выбора устройства приложение практически мгновенно запустится на нем.

Пока ваше приложение работает, вы можете открыть пункт Android Monitor внизу экрана и следить за всеми сообщениями от приложения на вкладке LogCat, рядом также есть логи Android Studio, так что если что-то пойдет не так вы сможете решить проблему. Если что-то пойдет не так, ищите там красный текст, он поможет понять что произошло. Это сэкономит очень много времени.

Там же можно переключиться на вкладку "Monitors" и посмотреть информацию об устройстве, нагрузку на процессор, память и так далее.

6. ADV Manager

Вряд ли вы бы захотели пользоваться Android Studio и разрабатывать приложения без реального устройства. Но одна из самых важных проблем Android разработки - это фрагментация. Недостаточно чтобы приложение работало на вашем устройстве, оно должно работать на миллионах устройств, а также поддерживать более старые версии Android.

С помощью Android Virtual Device вы можете эмалировать размер, внешний вид, мощность любого другого устройства Android. Но перед тем как перейти дальше, нужно скачать необходимые компоненты. Откройте меню "Tools" -> "Android" -> "ADV Manager":

Здесь выберите "Create Virtual Device" :

Затем выберите модель устройства, которое хотите эмулировать.




После завершения настройки вы сможете запустить приложение и на этом устройстве. Но стоит отметить, что для запуска эмулятора нужен хороший компьютер. С помощью того же эмулятора вы можете запускать не только свои приложения, но и загружать сторонние из Play Market.

8. SDK Manager

Если вы разрабатываете приложение только для определенной версии Android или же хотите создать виртуальное устройство под управлением определенной версии, то вам понадобятся некоторые компоненты и инструменты SDK. Вы можете получить их через SDK Manager, который находится в "Tools" -> "SDK Manager".


Здесь есть все необходимое, например, Glass Kit и Android Repository. Просто установите флажок рядом с нужным компонентом и нажмите "Oк" .

9. Упаковка APK

Рано или поздно вы закончите тестирование своего приложения и оно будет готово выйти в большой мир. Чтобы загрузить его на Google Play вам нужно создать подписанный APK. Для этого выберите в меню "Tools" пункт "Create signed APK":

Вам будет предложено выбрать или создать хранилище ключей. Это своего рода сертификат подлинности, которым вы подтверждаете, что приложение ваше. Это защитит ваш аккаунт Google Play от взлома и предотвратит возможность загрузки вредоносных APK. Сохраните этот файл в надежном месте, потому что если вы его потеряете, то больше не сможете обновить приложение. Процесс создания сертификата:





Тип сборки выберите "Release" , это нужно чтобы убрать все лишнее из APK файла. Затем нажмите кнопку "Finish" .

Ваш путь только начинается

Может показаться, что в этой статье мы рассмотрели очень много чтобы все это запомнить, но на самом деле мы только коснулись поверхности того, как пользоваться Android Studio и вам придется освоить еще больше.

Например, если вы хотите синхронизировать приложение с облаком, вам понадобится инструмент Firebase. Также вы можете захотеть использовать GitHub, где вы можете сохранять резервные копии своих проектов. Также существует Android NDK для разработки приложений без Java, на C++.

Компания Google сделала множество шагов чтобы использование Android Studio было простым и максимально легким. Лучшая стратегия развития - начать разрабатывать простое приложения и по мере необходимости изучать сложные библиотеки, тогда вы увидите что Android Studio на самом деле замечательный и очень полезный инструмент.

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.



Рекомендуем почитать

Наверх