- Правильная работа с файлами в Android
- lopspower / README.md
- Android File System And Directory Structure Explained
- Android File System Structure
- The sdcard and ext-sdcard Partitions
- Card Type
- Card Type File System
- Max Capacity
- Android File Associations
- Android File Managers
- File Downloads
- Summary
- Data and file storage overview
- Categories of storage locations
- Permissions and access to external storage
- Scoped storage
- View files on a device
- Additional resources
- Videos
Правильная работа с файлами в Android
Сегодня я бы хотел рассказать вам о правильной работе с файлами в ОС Android. Итак, чаще всего у новичков возникают ситуации, когда обычные Java функции не могут корректно создать тот или иной файл в системе Android.
Во-первых, вам нужно обратить внимание на интересную особенность ОС:
когда вы устанавливаете apk приложение в эмулятор или телефон, система Linux (на которой базируется ядро Android) выделяет ему специальный User-ID, который является неким ключом доступа к (sandbox). То есть другие приложения в телефоне не смогут получить доступ к чтению файлов вашего приложения просто так. Кончено, всё это сделано в целях безопасности.
В общем, если вы запустите следующий код:
FileWriter f = new FileWriter(«impossible.txt»);
То этот код вызовет исключение: ‘java.io.FileNotFoundException: /impossible.txt ‘
Тогда как должен в случае отсутствия файла создать его.
Далее стоит отметить, что данное ограничение не распространяется на файлы, записываемые на SDCard. Туда можно писать любые файлы без всяких проблем, правда предварительно нужно добавить в AndroidManifest разрешение на запись:
Код файла на карту:
File fileName = null;
String sdState = android.os.Environment.getExternalStorageState();
if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) <
File sdDir = android.os.Environment.getExternalStorageDirectory();
fileName = new File(sdDir, «cache/primer.txt»);
> else <
fileName = context.getCacheDir();
>
if (!fileName.exists())
fileName.mkdirs();
try <
FileWriter f = new FileWriter(fileName);
f.write(«hello world»);
f.flush();
f.close();
> catch (Exception e) <
>
Как уже ранее было сказано мною, android приложение находится в некой песочнице, изолированной от воздействия со стороны других приложений по умолчанию. Для того, чтобы создать файл внутри этой песочницы, следует использовать функцию openFileOutput(). Хочу отметить 2 аргумента:
1. имя файла
2. режим доступа к нему со стороны чужих приложений
С первым аргументом все ясно, что касается второго, то режимов существует два: MODE_WORLD_READABLE и/или MODE_WORLD_WRITEABLE.
И ещё, чтобы записать файл можно использовать следующий код:
final String TESTSTRING = new String(«Hello Android»);
FileOutputStream fOut = openFileOutput(«samplefile.txt», MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// записываем строку в файл
osw.write(TESTSTRING);
/* проверяем, что все действительно записалось и закрываем файл */
osw.flush();
osw.close();
Для чтения файлов используется метод openFileInput():
FileInputStream fIn = openFileInput(«samplefile.txt»);
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[TESTSTRING.length()];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
Для удаления используется метод deleteFile() в контексте приложения/активити. На этом я бы хотел закончить полезный пост, спасибо за внимание!
Источник
lopspower / README.md
All Android Directory Path
1) System directories
⚠️ We can’t write to these folers
Method | Result |
---|---|
Environment.getDataDirectory() | /data |
Environment.getDownloadCacheDirectory() | /cache |
Environment.getRootDirectory() | /system |
2) External storage directories
⚠️ Need WRITE_EXTERNAL_STORAGE Permission
Method | Result |
---|---|
Environment.getExternalStorageDirectory() | /storage/sdcard0 |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS) | /storage/sdcard0/Alarms |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) | /storage/sdcard0/DCIM |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) | /storage/sdcard0/Download |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) | /storage/sdcard0/Movies |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) | /storage/sdcard0/Music |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS) | /storage/sdcard0/Notifications |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) | /storage/sdcard0/Pictures |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS) | /storage/sdcard0/Podcasts |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES) | /storage/sdcard0/Ringtones |
3) Application directories
Method | Result |
---|---|
getCacheDir() | /data/data/package/cache |
getFilesDir() | /data/data/package/files |
getFilesDir().getParent() | /data/data/package |
4) Application External storage directories
Источник
Android File System And Directory Structure Explained
Last Updated: November 7, 2014
Most people are familiar with the file layout on Windows and are happy navigating the Windows file System.
Windows uses a drive letter for each physical drive or partition.e.g. C: drive
Note: A Physical drive will have at least 1 partition but can have more than one. This is true for both Windows and Android.
[outline style=”yellow”]What is a Disk Partition? – Disks can be subdivided into smaller disks called partitions. Partitions appear and can be used as if they were separate physical disks. [/outline]
If you insert a USB drive into your windows machine in shows up as a disk with an assigned drive letter.
Although windows shows a disk icon the disks could be partitions of a single physical disk.
Each disk partition has a root directory which contains files and folders (directories).
The root of the C drive is C:\ and of the F drive is F:\ etc
Android File System Structure
Android uses the Linux file system structure which has a single root .
The diagram below shows the structure
The system partitions and directories are protected and unless your device is rooted you don’t normally have access to these although some file managers will display them.
Physical disks and partitions appear under the root as a directories , and do not have a drive letter as in Windows.
Android doesn’t normally come with a default file manager, and so you will need to install a file manager App like Astro file manager, to locate and manage files and folders.
The sdcard and ext-sdcard Partitions
The sdcard partition is the main storage area for user data and files. It also contains App settings and data.
The sdcard partition exists even though you may not have an external sd card.
It is the internal partition.
If you open the sdcard directory you will see something like this:
Note: partial listing only
These files and directories contain your pictures,films,downloads etc as well as App data and settings.
You can view these files from your PC by connecting your device to a PC using a USB cable.
The ext-sdcard partition will only be visible if your device supports external storage, usually using a microSD slot.
External sd cards use either the FAT,FAT32 or exFAT file system formats.
Most devices support FAT and FAT32, but support for exFAT is limited.
The choice of file system is governed by the partition size as follows:
Card Type
Card Type File System
Max Capacity
Note: Windows format size limit of 32GB. Can be larger but need to format using external tools. Windows XP could fomat FAT32 Volumes upto 128 GB
Android File Associations
Just as with other operating systems like Windows, Android will use an App to open a particular file type,denoted by the extension.
For example if you try to open a pdf file it will normally use Adobe reader (if installed) to open the file.
To open a file you will normally need to located the file using a file manager.
Just press the file to open it.
If the file type doesn’t already have an App associated with it you should be prompted to choose between the available Apps.
The option to always use that App sets it as the default App for that file type.
If you set it as the default App you will not be prompted again unless you remove the association.
To remove an association you need to remove it from the App itself.
So if the pdf files open with adobe reader and you want to change that:
- Go to Settings>Apps>Select Adobe reader,
- Then go to the Launch by default section
- and Clear defaults
The next time you try to open a pdf file you will be promoted to choose an App.
Android File Managers
If you search the Google play store you will find many file managers.
Which App is the most suitable depends on what you want to do. You should bear in mind that more features/functionality isn’t always better.
File managers like ESF have lots of functionality including:
- Built in FTP client
- Task Manager
- Cloud storage client
- etc
However for many this is a bit of an overkill, and so you might consider installing one of the simpler file managers like file manager and Astro file manager.
File Downloads
When you download a file using Google chrome or another browser App the file it is stored in the download directory.
You can access the directory contents through a shortcut in the Apps folder (if provided).
You can also use a file manager to locate it the folder called download. It is under your primary storage (called sdcard)
Summary
Android uses the Linux File and Directory Structure which consists of a single root.
All drives and partitions are displayed as directories in this tree like structure.
Источник
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.
Источник