Write to.txt file

Asked

Viewed 3,011 times

2

I am developing an application that needs to record data in the database and go saving these same data in a arquivo.txt in the device’s memory. The bank part is ok, now in the file part I have not found any documentation exemplifying yet. If you can give me the link of some specific documentation or someone to demonstrate how to implement it, I am very grateful.

obs. At each new insertion, I need to concatenate the new value to the old value thus creating a list of contents in the arquivo.txt. Ex:

date1;values

date2;values

date3;

  • If u will save key-value pairs because it does not use sharedPreferences?

  • Why save to txt?

  • In reality the values are just an example, I need to save much more information... This text file I need to generate will also be a kind of "Backup of information", because in a later procedure the database will receive a delete, however this text file has to be saved. The text file will also serve as a "log" of the information. As if it were a redundancy of information. If Sqlite fails, it has several reasons...

2 answers

3

First you have to give permission to read and write on your AndroidManifest.xml. Behold:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Remembering that you should watch and start from Android 6.0 (API level 23), users grant permissions to applications while they are running, not when they are installed. See more details about request for runtime permissions.

This approach optimizes the application installation process, as the user does not need to grant permissions when installing or updating application. It also gives the user more control over the app features.

Hand in the cookie jar

Once this is done, you can create a method by passing the context, the file name and the file contents as a parameter for recording. See how it would look:

public void gerarArquivo(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();

        //aqui você exibe na tela uma mensagem que o arquivo foi salvo
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

To read the contents of the file, you can create a method by passing as parameter the name of the file in which its return will be one String. See how it would look:

public static String lerArquivo(String rFilename) {

    File sdcard = Environment.getExternalStorageDirectory();    
    File file = new File(sdcard, rFilename);    
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        br.close();
    } catch (IOException e) {
        // exibir erro caso não funcione
    }

    return text.toString();
}

For more details you can read in the documentation about save files internally and externally. If the device does not have an external location to save, the ideal is to put a condition in which it checks and saves the file in the most appropriate location.

References

  • I understood your placement. And if I prefer to save in the device’s internal storage?

  • @fvmoraes made an edition for better understanding.

0

It is very similar to the file system on the desktop. Using the Android Developers, use File:

File arquivo = new File(context.getFilesDir(), "arquivo.txt");
FileOutputStream output = new FileOutputStream(arquivo);
// escreva os dados aqui com output

Browser other questions tagged

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