Android data file editor

Работа с файловой системой

Чтение и сохранение файлов

Работа с настройками уровня activity и приложения позволяет сохранить небольшие данные отдельных типов (string, int), но для работы с большими массивами данных, такими как графически файлы, файлы мультимедиа и т.д., нам придется обращаться к файловой системе.

ОС Android построена на основе Linux. Этот факт находит свое отражение в работе с файлами. Так, в путях к файлам в качестве разграничителя в Linux использует слеш «/», а не обратный слеш «\» (как в Windows). А все названия файлов и каталогов являются регистрозависимыми, то есть «data» это не то же самое, что и «Data».

Приложение Android сохраняет свои данные в каталоге /data/data/ / и, как правило, относительно этого каталога будет идти работа.

Для работы с файлами абстрактный класс android.content.Context определяет ряд методов:

boolean deleteFile (String name) : удаляет определенный файл

String[] fileList () : получает все файлы, которые содержатся в подкаталоге /files в каталоге приложения

File getCacheDir() : получает ссылку на подкаталог cache в каталоге приложения

File getDir(String dirName, int mode) : получает ссылку на подкаталог в каталоге приложения, если такого подкаталога нет, то он создается

File getExternalCacheDir() : получает ссылку на папку /cache внешней файловой системы устройства

File getExternalFilesDir(String type) : получает ссылку на каталог /files внешней файловой системы устройства

File getFileStreamPath(String filename) : возвращает абсолютный путь к файлу в файловой системе

FileInputStream openFileInput(String filename) : открывает файл для чтения

FileOutputStream openFileOutput (String name, int mode) : открывает файл для записи

Все файлы, которые создаются и редактируются в приложении, как правило, хранятся в подкаталоге /files в каталоге приложения.

Для непосредственного чтения и записи файлов применяются также стандартные классы Java из пакета java.io.

Итак, применим функционал чтения-записи файлов в приложении. Пусть у нас будет следующая примитивная разметка layout:

Поле EditText предназначено для ввода текста, а TextView — для вывода ранее сохраненного текста. Для сохранения и восстановления текста добавлены две кнопки.

Теперь в коде Activity пропишем обработчики кнопок с сохранением и чтением файла:

При нажатии на кнопку сохранения будет создаваться поток вывода FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE)

В данном случае введенный текст будет сохраняться в файл «content.txt». При этом будет использоваться режим MODE_PRIVATE

Система позволяет создавать файлы с двумя разными режимами:

MODE_PRIVATE : файлы могут быть доступны только владельцу приложения (режим по умолчанию)

MODE_APPEND : данные могут быть добавлены в конец файла

Поэтому в данном случае если файл «content.txt» уже существует, то он будет перезаписан. Если же нам надо было дописать файл, тогда надо было бы использовать режим MODE_APPEND:

Для чтения файла применяется поток ввода FileInputStream :

Подробнее про использование потоков ввода-вывода можно прочитать в руководстве по Java: https://metanit.com/java/tutorial/6.3.php

В итоге после нажатия кнопки сохранения весь текст будет сохранен в файле /data/data/название_пакета/files/content.txt

Где физически находится созданный файл? Чтобы увидеть его на подключенном устройстве перейдем в Android Stud в меню к пункту View -> Tool Windows -> Device File Explorer

После этого откроектся окно Device File Explorer для просмотра файловой системы устройства. И в папке data/data/[название_пакета_приложения]/files мы сможем найти сохраненный файл.

Источник

Store User Data Using Simple Text Files and APIs in Android

Android apps have a wide variety of features, functionalities, and purposes. These various Android apps require similarly varied support from Android system APIs. Many apps require storing data in short-term memory that lasts only as long as the app is running. But, some apps need to store data or user preferences persistently, so that user data and user preferences are maintained indefinitely. In this article, we are going to demonstrate how we can store data in files, and also how can we store user preferences using Android APIs. We’ll create two small apps: one to store an read a file from user input, and one to store user preferences.

Читайте также:  Android tv box молдове

Creating the UI of the File Store App

Lets start by creating a simple app that shows an text editor and allows the user can input any text to be saved as a file.The saved text will be saved within the text editor next time the application is started by reading from the storage file.

First, we’ll create the UI for the app. Within the UI we are going to create a text editor and a save button on screen.

The layout for this UI is as follows:

Above, we create a text view using the tag

, which just displays the text as “Enter The Text”.

Next, we create an editor to take in the text from the user. We create this using the tag, and because we want the text to be multi-line, we also set the properties android:singleLine=“false” and android:lines=“10” on the EditText. Then, we create a button using the tag, which will be used to save the modified text to a file.

Once the layout is created, we’ll use the function onCreate to set this layout of the content view as follows:

Now, if we run the app, the UI will look as follows:

Saving the File

Once the UI is done, we need to add functionality to save the text contents to a file upon pressing the “Save” button. To do this, the code is as follows:

Once “Save” is clicked, the function saveClicked is called. In the function saveClicked, we open a file using the Android API openFileOutput by passing it the name of the file to open, which we defined in our class as

Then, we create an object of OutputStreamWriter using the output of openFileOutput.

Finally, we get the text of the text editor and pass it to the write method of our OutputStreamWriter to write it to the file. Once the text is written to the file, we show a Toast to indicate that the text is saved. Below, the Toast reads “The contents are saved in the file.”

Reading the Text File Upon App Load

Now, let’s write a function that reads this newly-created file and populates the text editor with the contents of the file. We will call this function in the onCreate function so that as soon as the app launches, the editor is filled with the information from the file. The function is as follows:

In this function, we first open the file with the API openFileInput, and then we create an InputStream from it. From that, we create an InputStreamReader and a BufferedReader. Using the BufferedReader, we read line after line the text of the storage file, and we store the text in the buffer. Once the whole file is read, we send the text into the editor. Now, if the application is run, the application will load the the editor filed with the contents of the file, as shown below.

Shared Preferences Introduction

Shared preferences allow you to store key => value pairs of different settings that you want within your Android app, even if the app session is closed. You can store a number of native preference types, such as Boolean, int, strings, etc. Below, we are going to create a small app in which the user can store the preference of whether he wants the activities background color as blue or red.

Creating a UI for storing Preferences

First, we must create the UI of the app. The layout for the app will be as follows:

Above, we create a linear layout and then add a TextView to display the message that asks the user to select his background color preference. Then, we create a radio button group with two radio button to give the two color options to the user. Lastly, we create a button that will save the user’s color preference upon being pressed..

If we run the app now, the UI will look like this:

Saving the Preferences

Now, lets see how we can save the preference that the user has selected. The code to save the preference is as follows in the functionВ saveBgColorPreference.

Читайте также:  Регистратор антирадар для андроида

In this function, we get the RadioGroup, and we find the ID of the radio button that was selected. Then, we get the text of the selected radio button to check which color the user has selected. Then, we get the SharedPreferences object using the function getSharedPreferences. Because we want to edit the shared preferences, we have to get the SharedPreferences.Editor and then call the function putString on it to write the string and then call commit to finish the writing transaction. This will store the color value within the stored preferences.

Using the Saved Preferences to Change Properties of the App

Now that we’ve written code to store the user’s color preference, we will write a function setColorOnPreference to actually change the background color according to the preference. The function is as follows:

In this function we get the linear layout using its ID. Then, we get the shared preferences object using the function getSharedPreferences. Then, using the function getString, we get the background color preference.

If the background color is blue, we set the background to blue. Otherwise, we set it to red.

Now, upon pressing the button, we will call the function savepreferencesClicked, which is as follows:

In order to start the app with the desired background color (of the users choice), we will call setColorOnPreference in onCreate as follows:

Now, if we run the app it will look as follows:

Now, if we select and change the color to red and save it the app will make (and store as a user preference) the following color change:

Conclusion

Android APIs provide good support for developers who want to share persistent data between two different sessions of an Android application. Using files and preferences APIs, we can store user data and preferences to make the application more personalized and practical for the end users. The flexibility with which the APIs are designed has made their use very simple, and apps can be developed very quickly using these powerful APIs. So, happy Android app development!

Источник

Data and file storage overview

Android uses a file system that’s similar to disk-based file systems on other platforms. The system provides several options for you to save your app data:

  • App-specific storage: Store files that are meant for your app’s use only, either in dedicated directories within an internal storage volume or different dedicated directories within external storage. Use the directories within internal storage to save sensitive information that other apps shouldn’t access.
  • Shared storage: Store files that your app intends to share with other apps, including media, documents, and other files.
  • Preferences: Store private, primitive data in key-value pairs.
  • Databases: Store structured data in a private database using the Room persistence library.

The characteristics of these options are summarized in the following table:

Type of content Access method Permissions needed Can other apps access? Files removed on app uninstall?
App-specific files Files meant for your app’s use only From internal storage, getFilesDir() or getCacheDir()

From external storage, getExternalFilesDir() or getExternalCacheDir()

Never needed for internal storage

Not needed for external storage when your app is used on devices that run Android 4.4 (API level 19) or higher

No Yes
Media Shareable media files (images, audio files, videos) MediaStore API READ_EXTERNAL_STORAGE when accessing other apps’ files on Android 11 (API level 30) or higher

READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE when accessing other apps’ files on Android 10 (API level 29)

Permissions are required for all files on Android 9 (API level 28) or lower

Yes, though the other app needs the READ_EXTERNAL_STORAGE permission No
Documents and other files Other types of shareable content, including downloaded files Storage Access Framework None Yes, through the system file picker No
App preferences Key-value pairs Jetpack Preferences library None No Yes
Database Structured data Room persistence library None No Yes

The solution you choose depends on your specific needs:

How much space does your data require? Internal storage has limited space for app-specific data. Use other types of storage if you need to save a substantial amount of data. How reliable does data access need to be? If your app’s basic functionality requires certain data, such as when your app is starting up, place the data within internal storage directory or a database. App-specific files that are stored in external storage aren’t always accessible because some devices allow users to remove a physical device that corresponds to external storage. What kind of data do you need to store? If you have data that’s only meaningful for your app, use app-specific storage. For shareable media content, use shared storage so that other apps can access the content. For structured data, use either preferences (for key-value data) or a database (for data that contains more than 2 columns). Should the data be private to your app? When storing sensitive data—data that shouldn’t be accessible from any other app—use internal storage, preferences, or a database. Internal storage has the added benefit of the data being hidden from users.

Categories of storage locations

Android provides two types of physical storage locations: internal storage and external storage. On most devices, internal storage is smaller than external storage. However, internal storage is always available on all devices, making it a more reliable place to put data on which your app depends.

Removable volumes, such as an SD card, appear in the file system as part of external storage. Android represents these devices using a path, such as /sdcard .

Apps themselves are stored within internal storage by default. If your APK size is very large, however, you can indicate a preference within your app’s manifest file to install your app on external storage instead:

Permissions and access to external storage

On earlier versions of Android, apps needed to declare the READ_EXTERNAL_STORAGE permission to access any file outside the app-specific directories on external storage. Also, apps needed to declare the WRITE_EXTERNAL_STORAGE permission to write to any file outside the app-specific directory.

More recent versions of Android rely more on a file’s purpose than its location for determining an app’s ability to access, and write to, a given file. In particular, if your app targets Android 11 (API level 30) or higher, the WRITE_EXTERNAL_STORAGE permission doesn’t have any effect on your app’s access to storage. This purpose-based storage model improves user privacy because apps are given access only to the areas of the device’s file system that they actually use.

Android 11 introduces the MANAGE_EXTERNAL_STORAGE permission, which provides write access to files outside the app-specific directory and MediaStore . To learn more about this permission, and why most apps don’t need to declare it to fulfill their use cases, see the guide on how to manage all files on a storage device.

Scoped storage

To give users more control over their files and to limit file clutter, apps that target Android 10 (API level 29) and higher are given scoped access into external storage, or scoped storage, by default. Such apps have access only to the app-specific directory on external storage, as well as specific types of media that the app has created.

Use scoped storage unless your app needs access to a file that’s stored outside of an app-specific directory and outside of a directory that the MediaStore APIs can access. If you store app-specific files on external storage, you can make it easier to adopt scoped storage by placing these files in an app-specific directory on external storage. That way, your app maintains access to these files when scoped storage is enabled.

To prepare your app for scoped storage, view the storage use cases and best practices guide. If your app has another use case that isn’t covered by scoped storage, file a feature request. You can temporarily opt-out of using scoped storage.

View files on a device

To view the files stored on a device, use Android Studio’s Device File Explorer.

Additional resources

For more information about data storage, consult the following resources.

Videos

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Читайте также:  Пароль от вай фая android пароль
Оцените статью