Data saving on Android

Asked

Viewed 7,881 times

4

I have a project based on the following 'folders' structure that will be saved some data in the external memory:

/AppName

Example1 [ Text files and etc. ]
Example2 [ Text files and etc. ]

Let’s say I need to save multiple text files in these two folders. What’s the best way? Save text files to external memory And in the application files (raw Folder) or save the text files ONLY in the application files and NAY create a folder to save these files.

Which is the best option?

  • 1

    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.

  • 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!

  • In the case of Internal Storage, just use getFilesDir in an instance of Context to get a File 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), the getFilesDir returns a File 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".

  • Got it. Thanks a lot, Wakim. Hugs! p

1 answer

4

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.

inserir a descrição da imagem aqui

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.

inserir a descrição da imagem aqui

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/

  • 1

    Hello, Lollipop. Thank you so much for your answer. It helped me solve several issues I had regarding this. I’ve decided which storage method to use thanks to your response and Wakim’s comment. I believe it will serve several people who have the same doubt. Hugs!

  • @C0rey, mark as solved!

  • @Lollipop, I think there is a translation error, in the documentation and in the source you indicated says that files from internal storage are also deleted when uninstalling the app

  • @underchild Only if it is Private files, ie that is within the app package in: Android / data / [package name] / files / on external storage

  • @Lollipop, on the website where he translated it says that internal files are deleted ("and gets purged when the app is uninstalled") and not that it will be saved, the documentation also says that they are deleted (https://developer.android.com/guide/topics/data/storage.html#filesInternal), I think it would be nice to fix because I even mistook it a lot when I read it (I also tried uninstalling an app with files in internal memory, and they were lost)

  • credit for answering my question: https://answall.com/questions/278139/porque-arquivos-do-app-permanecerm-ap%C3%b3s-a-uninstall%C3%A7%C3%a3o

  • Altered........

  • in this example you put above, ta a print com.pycitub.pyc, there you say that it does not erase, however this structure you posted is of the date/date that is not accessible to the normal user, only user with SUPER SU or better root when uninstalling the application this folder is removed...

  • adding, today the android system has changed a lot, and for example these phones that have 64 internal, let’s assume 3 gigas are for the system, and the rest is pro user, but the user does not see everything, this date/date is only possible to see above Storage/Emulated/0 levels the zero folder is the one the common user has access to that date folder is at the same root as the Storage folder is... from a look at images > https://imgur.com/a/GMEqk

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.