All Android devices have two types of file storage options - internal and external. Read this article and you will see that the best option will be according to the need of your app:
Internal storage
This storage area is a kind of area privada
for the application. It is always available for the application and will be saved even when the application is uninstalled by the user. Let’s quickly see how to write a file to the internal storage:
// Create um arquivo no Internal Storage
String fileName = "MeuArquivo";
String content = "Olá todos?";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
This should immediately create a file called Myfile with the contents Hello everyone?. The internal storage directory is usually found in a special location specified by the package name of our app. In my case it is /data/data/[package name] and the files created are stored in a directory called files in that directory.
Note: The constant Context.MODE_PRIVATE
makes the file inaccessible to other applications. If you want other applications to access your files, then it might be better to save them to external storage.
In order to cache some data, that is, create cache files instead of storing data in files persistently, we can open an object file that represents the cache directory in the internal memory using getCacheDir(). Let’s see some code to create cache files.
Conteúdo String = "Olá mundo" ;
Arquivo do arquivo;
FileOutputStream outputStream;
tente {
// File = File.createTempFile ("MyCache", null, getCacheDir ());
file = novo Arquivo (getCacheDir (), "MyCache" );
outputStream = novo FileOutputStream (arquivo);
outputStream.write content.getBytes (());
outputStream.close ();
} prendedor (IOException e) {
e.printStackTrace ();
}
This creates cache files in a directory called cache.
When the device has little internal storage space, cache files are erased to regain space. According to the documentation we should not rely on the automatic cleaning mechanism. Instead, we should delete cache files and make sure they don’t consume more than 1MB .
If we use getFilesDir() instead of getCacheDir(), then it will store files in the directory files making the code, with effect similar to the previous example. Also, note the commented line that uses File.createTempFile() to create the file. You can use this version too if you like, but remember that the generated file will have random suffix characters. This is done to keep the file name unique by this method. Therefore, a way to keep track of what is to store the file names in a database and then reference, but for a simple task that can be an exaggeration.
If you want to quickly read your files, then here is the code to do this exact job:
BufferedReader entrada = nulo ;
Arquivo File = nulo ;
tente {
file = novo Arquivo (getCacheDir (), "MyCache" ); // Passe getFilesDir () e "MyFile" para ler o arquivo
input = nova BufferedReader ( novo InputStreamReader ( novo FileInputStream (arquivo)));
Linha String;
Tampão StringBuffer = novo StringBuffer ();
enquanto ((linha = input.readLine ())! = NULL ) {
buffer.append (linha);
}
Log.d (TAG, buffer.toString ());
} prendedor (IOException e) {
e.printStackTrace ();
}
External storage
Android devices supports another type of storage called external storage, where applications can save files. It can be removable, such as an SD card or non-removable, in which case it is internal. The files in this storage are read by everyone, which means other applications have access to them and the user can transfer them to his computer by connecting to a USB.
Using getExternalStorageState()
we can obtain the current state of the primary external storage device. If it is equal to Environment.MEDIA_MOUNTED
then we will have read/write access and if it is equal to Environment.MEDIA_MOUNTED_READ_ONLY
then we just have read access.
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
Although external storage is accessible and modifiable by user and other applications, you can save the files in two ways - públicas
and privadas
. Before we discuss these two types note that in order to read and/or write files to external storage we will need the READ_EXTERNAL_STORAGE
and WRITE_EXTERNAL_STORAGE
system permissions. The latter covers both reading and writing. Although starting with Android 4.4 Kitkat (API 19), reading and writing private files in private external storage directories do not require permissions on Androidmanifest.xml.
Public archives
Files that will remain in storage even after the application is uninstalled by the user as media (photos, videos, etc.) or other downloaded files. There are two methods we can use to get the public directory from external storage to place files:
getExternalStorageDirectory() - This returns (top level or root) external primary storage directory.
getExternalStoragePublicDirectorty() - This returns a top-level public external directory of storage for pushing files of a particular type, based on the past argument. So, basically, the external storage has directories like Music, Podcasts, Pictures, etc., whose paths can be determined and returned through this function, passing the appropriate environment constants.
Let’s quickly save a file in the external storage directory:
Conteúdo String = "Olá mundo" ;
Arquivo do arquivo;
FileOutputStream outputStream;
tente {
file = novo Arquivo (Environment.getExternalStorageDirectory (), "MyCache" );
outputStream = novo FileOutputStream (arquivo);
outputStream.write content.getBytes (());
outputStream.close ();
} prendedor (IOException e) {
e.printStackTrace ();
}
As simple as that! You can try Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS) instead of Environment.getExternalStorageDirectory () to save the file in the downloads directory of your external storage.
THIS SO(https://stackoverflow.com/a/6049446) answer has some additional details regarding these methods worth reading and knowing.
Private archives
These files will be accessible to other applications, but are in such a way that they do not provide any value to other applications or even to the user outside the context of the app as certain files downloaded by a media game (audio, images, etc.).
Saving files to the appropriate directories for carrying out your private files is super easy. You can try the previous examples, but use getExternalFilesDir () to get the appropriate directory path. Again environment constants like DIRECTORY_MUSIC or DIRECTORY_PICTURES can be passed or you can also pass null to return the root directory to your app’s private directory on volume. The path must be Android / date / [package name] / files / on external storage. You can check out the new files created in Android File Transfer, adb shell or ES File Explorer.
Similar to getCacheDir() in terms of internal storage, we also have getExternalCacheDir() to save external cache files.
SOURCE: http://codetheory.in/android-saving-files-on-internal-and-external-storage/
The big difference I see between these two alternatives would be safety. In External Storage, although there is more space, the user and any other app can access/modify these files/folders. In Internal Storage, you only have the security of seeing your app (unfortunately, users with root can access this area if you have sensitive files take care), but space is limited. If you can, clarify better the purpose behind, if it is some requirement or just organization.
– Wakim
Thanks for the comment. The purpose is organization itself. For example, if I create a file . ini and put in raw folder, where this file will stop? What if I put in external memory? Remembering: are not data that need to be *safe. Thank you very much for the comment!
– C0rey
In the case of
Internal Storage
, just usegetFilesDir
in an instance ofContext
to get aFile
to the root directory of your app. There you can manipulate and create your directory and file structure. The app’s are in the folder/data/data/nome_do_pacote
or/data/app/nome_do_pacote
device (only with root you can see this directory), thegetFilesDir
returns aFile
to your app directory, there you can organize your files there. Keep in mind that space is limited (each device has a different Internal Storage) and it is good not to "abuse".– Wakim
Got it. Thanks a lot, Wakim. Hugs! p
– C0rey