Android read all files from directory

Android read all files from directory

Android supports all the standard Java file I/O APIs for create, read, update, and delete (CRUD) operations, along with some additional helpers to make accessing those files in specific locations a little more convenient. There are three main locations in which an application can work with files:

  • Internal storage. Protected directory space to read and write file data. Internal storage is always located in the device’s flash memory area — part of the 8 GB or 32 GB of «storage» that your device was advertised with—under /data/data/PKG_NAME/.
  • External storage. Externally mountable space to read and write file data. Requires the WRITE_EXTERNAL_STORAGE permission in API Level 4+. Often, this is a physical SD card in the device.
  • Assets. Protected read-only space inside the APK bundle. Good for local resources that can’t or shouldn’t be compiled.

However, there are several complications.

First, some devices don’t have removable storage. On these, the external storage directory always exists—it is just in a different partition of the same flash memory storage as internal storage.

Second, on devices that do have removable storage, the storage might be removed at the time your application checks it. There’s no point trying to write it if it’s not there.

Read from res directory

If your application requires external file resources, you can include them in your distribution package by placing them in the res/raw folder of your project hierarchy.

To access these read-only file resources, call the openRawResource method from your application’s Resource object to receive an InputStream based on the specified file. Pass in the filename (without the extension) as the variable name from the R.raw class, as shown in the following code

Read from assets directory

Android offers one more directory where you can keep files which also will be included in package. This directory called /assets. There are some difference from res directory.

With resources, there’s built-in support for providing alternatives for different languages, OS versions, screen orientations, etc., as described here. None of that is available with assets. Also, many parts of the API support the use of resource identifiers. Finally, the names of the resources are turned into constant field names that are checked at compile time, so there’s less of an opportunity for mismatches between the code and the resources themselves. None of that applies to assets.source

Read/Write to Internal Storage

This area of storage is sort of private to the application. It is always available to the application and gets purged when the app is uninstalled by the user.

Internal storage refers to the hard drive on device. Internal storage gives you the ability to prevent other applications from accessing the files you save and are tied directly to your app.

Files stored in /data/data/packagename/files/filename.txt. There are few modes for file access

  • MODE_PRIVATE — create a new file or overwrite one if it already exists with the same name
  • MODE_APPEND — create the file if it doesn’t exist and allow you to append to the file if it does exist
  • MODE_WORLD_READABLE — file is readable by any other application
  • MODE_WORLD_WRITEABLE — file is writeable by any other application

Internal storage can be accessed using the Context methods openFileInput(String filename) , which returns a FileInputStream object, or openFileOutput(String filename, int mode) , which returns a FileOutputStream .

Write to file in internal storage

Read from file in internal storage

The Context method getFilesDir() returns the root of this directory, and you can then access it using normal java.io methods and classes.

Data is written to the file streams as bytes, so higher-level data (even strings) must be converted into and out of this format.

Following is a method to save an image to internal storage in Kotlin

Read/Write to SDCard

The key differentiator between internal and external storage is that external storage is mountable. This means that the user can connect his or her device to a computer and have the option of mounting that external storage as a removable disk on the PC. Often, the storage itself is physically removable (such as an SD card), but this is not a requirement of the platform.

External storage is typically either a removable storage media (i.e. SD Card) or an internal non-removable storage that is accessed in the same manner.

The most important thing to remember when storing files on external storage is that no security is enforced on files stored here. Any application can access, overwrite, or delete files stored on the external storage.

In order to write data to SDCard, the application need permission WRITE_EXTERNAL_STORAGE, which can be specified in the file AndroidManifest.xml.

Check external storage

Write to SDCard

Read from SDCard

Following is a method to save an image to external storage in Kotlin

Read/Write to Cache

Should your application need to cache temporary files, Android offers both a managed internal cache, and (since Android API level 8) an unmanaged external cache. You can access them by calling the getCacheDir and getExternalCacheDir methods, respectively, from the current Context.

Files stored in either cache location will be erased when the application is uninstalled. Files stored in the internal cache will potentially be erased by the system when it is running low on available storage; files stored on the external cache will not be erased, as the system does not track available storage on external media.

Read from cache dir

Write to cache dir

Read/Write to publicly readable files

Читайте также:  Damonps2 pro android bios

Android 2.2 (API level 8) includes a convenience method, Environment.getExternalStoragePublicDirectory , that can be used to find a path in which to store your application files. The returned location is where users will typically place and manage their own files of each type. Files that’ll remain on the storage even after the application is uninstalled by the user like media (photos, videos, etc.) or other downloaded files. This is particularly useful for applications that provide functionality that replaces or augments system applications, such as the camera, that store files in standard locations.

There are 2 methods that we can use to get the public external storage directory for placing files:

  • getExternalStorageDirectory() method returns the primary (top-level or root) external storage directory.
  • getExternalStoragePublicDirectorty method returns a top level public external storage directory for showing files of a particular type based on the argument passed. So basically the external storage has directories like Music, Podcasts, Pictures, etc. whose paths can be determined and returned via this function by passing the appropriate environment constants.

The getExternalStoragePublicDirectory method accepts a string parameter that determines which subdirectory you want to access using a series of Environment static constants:

  • DIRECTORY_DCIM — pictures and videos taken by the device
  • DIRECTORY_DOWNLOADS — files downloaded by the user
  • DIRECTORY_MOVIES — movies
  • DIRECTORY_MUSIC — audio fi les that represent music
  • DIRECTORY_PICTURES — pictures

Note that if the returned directory doesn’t exit, you must create it before writing fi les to the directory, as shown in the following snippet

External System Directories

There are additional methods in Environment and Context that provide standard locations on external storage where specific files can be written. Some of these locations have additional properties as well.

  • API Level 8
  • Returns a common directory where all applications store media files. The contents of these directories are visible to users and other applications. In particular, the media placed here will likely be scanned and inserted into the device’s MediaStore for applications such as the Gallery.
  • Valid type values include DIRECTORY_PICTURES , DIRECTORY_MUSIC , DIRECTORY_MOVIES , and DIRECTORY_RINGTONES .
  • API Level 8
  • Returns a directory on external storage for media files that are specific to the application. Media placed here will not be considered public, however, and won’t show up in MediaStore .
  • This is external storage, however, so it is still possible for users and other applications to see and edit the files directly: there is no security enforced.
  • Files placed here will be removed when the application is uninstalled, so it can be a good location in which to place large content files the application needs that one may not want on internal storage.
  • Valid type values include DIRECTORY_PICTURES , DIRECTORY_MUSIC , DIRECTORY_MOVIES , and DIRECTORY_RINGTONES .
  • API Level 8
  • Returns a directory on internal storage for app-specific temporary files. The contents of this directory are visible to users and other applications.
  • Files placed here will be removed when the application is uninstalled, so it can be a good location in which to place large content files the application needs that one may not want on internal storage.

Context.getExternalFilesDirs() and Context.getExternalCacheDirs() .

  • API Level 19
  • Identical features as their counterparts described previously, but returns a list of paths for each storage volume on the device (primary and any secondary volumes)
  • For example, a single device may have a block of internal flash for primary external storage, and a removable SD card for secondary external storage.
  • API Level 21
  • Files placed in these volumes will be automatically scanned and added to the device’s media store to expose them to other applications. These will generally also be visible to the user through core applications like the Gallery.

Sharing files via a FileProvider

Sometimes you want to share internal-storage files with another app, without the bother of putting the data into a Cursor and creating a ContentProvider.

The FileProvider class allows you to make files available to another application, usually in response to an Intent. It is simpler to set up than a ContentProvider , but is actually a subclass of ContentProvider .

This example exposes a photo.jpg file from one application to another. For this example I have created an Android Studio project called FileProviderDemo , which contains two different applications in two different packages, providerapp and requestingapp . We’ll start by discussing the Provider app since it contains the actual FileProvider . However, you have to run the Requester application first, as it will start the Provider app.

Unlike the ContentProvider case, you rarely have to write code for the provider itself; instead, use the FileProvider class directly as a provider in your AndroidManifest.xml file, as shown in following example.

The provider definition

The provider does not have to be exported for this usage, but must have the ability to grant Uri permissions as shown. The meta-data element gives the name of a simple mapping file, which is required to map «virtual paths» to actual paths, as shown.

The filepaths.xml file

Finally, there has to be an Activity to provide the Uri to the requested file. In our example this is the ProvidingActivity , shown in following example.

The important part of this code is in the provideFile() method, which:

  • Creates a Uri for the actual file (in this trivial example there is only one file, with a hardcoded filename)
  • Adds flags to the result Intent to let the receiving app read this one file (only) with our permissions
  • Sets the MIME type of the result
  • Adds the file Uri as data to the result Intent
  • Sets the result Intent , and the «success» flags to Activity.RESULT_OK • Calls finish() to end the Activity

Remember that the point of the FileProvider is to share files from one application to another, running with different user permissions. Our second application also has only one Activity , the «requesting» Activity. Most of this is pretty standard boilerplate code. In onCreate() , we create the requesting Intent :

Читайте также:  Поиск скрытого wifi android

The main part of the UI is a text area, which initially suggests that you request a file by pressing the button. That button’s action listener is only one line:

This will result in a subsequent call to onActivityComplete() , which is shown in following example.

Assuming that the request succeeds, you will get called here with requestCode set to the only valid action, RESULT_OK , and the resultIntent being the one that the providing Activity set as the Activity result—that is, the Intent wrapping the Uri that we need in order to read the file! So we just get the Uri from the Intent and open that as an input stream, and we can read the «secret» file from the providing application’s otherwise — private internal storage.

How to check free and used space in internal and external storage

There is auxiliary class to get information about free and used space in internal and external storage

How to download photo from url and save to storage

To download photo from url you can use android-async-http.

How to get file extension and mime type

You can get file extension and mime type:

Method to save an image to gallery and return URI in Kotlin

Источник

Saving Files

This lesson teaches you to

You should also read

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

A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it’s good for image files or anything exchanged over a network.

This lesson shows how to perform basic file-related tasks in your app. The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io .

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). Some devices divide the permanent storage space into «internal» and «external» partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.

  • It’s always available.
  • Files saved here are accessible by only your app by default.
  • When the user uninstalls your app, the system removes all your app’s files from internal storage.

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

  • It’s not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
  • It’s world-readable, so files saved here may be read outside of your control.
  • When the user uninstalls your app, the system removes your app’s files from here only if you save them in the directory from getExternalFilesDir() .

External storage is the best place for files that don’t require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.

Tip: Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. 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 App Install Location.

Obtain Permissions for External Storage

To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.

You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.

Save a File on Internal Storage

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir() Returns a File representing an internal directory for your app. getCacheDir() Returns a File representing an internal directory for your app’s temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it may delete your cache files without warning.

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

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here’s how to write some text to a file:

Or, if you need to cache some files, you should instead use createTempFile() . For example, the following method extracts the file name from a URL and creates a file with that name in your app’s internal cache directory:

Читайте также:  Как скрыть повторяющиеся контакты android

Note: Your app’s internal storage directory is specified by your app’s package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to 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 MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.

Save a File on External Storage

Because the external storage may 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 getExternalStorageState() . If the returned state is equal to MEDIA_MOUNTED , then you can read and write your files. For example, the following methods are useful to determine the storage availability:

Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:

Public files Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.

For example, photos captured by your app or other downloaded files.

Private files Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don’t provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app’s external private directory.

For example, additional resources downloaded by your app or temporary media files.

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

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() 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.

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

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

Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you’re saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory() .

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files that are private to your app, it’s important that you use directory names provided by API constants like DIRECTORY_PICTURES . These directory names ensure that the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.

Query Free Space

If you know ahead of time how much data you’re saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace() . These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.

However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace() . If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it’s probably safe to proceed. Otherwise, you probably shouldn’t write to storage.

Note: You aren’t required to check the amount of available space before you save your file. You can instead try writing the file right away, then catch an IOException if one occurs. You may need to do this if you don’t know exactly how much space you need. For example, if you change the file’s encoding before you save it by converting a PNG image to JPEG, you won’t know the file’s size beforehand.

Delete a File

You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.

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

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

  • All files you saved on internal storage
  • All files you saved on external storage using getExternalFilesDir() .

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

Источник

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