How to save ArrayList<String> or String[] array in .txt file in external storage in android

194 Views Asked by At

I have some strings in ArrayList and i want to save all strings in my android phone, i am using below method but it gives my o/p with extra numbers(garbage random values)

void storeFile(Context context, ArrayList<String> arrayList) {

    // Requesting Permission to access External Storage
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            EXTERNAL_STORAGE_PERMISSION_CODE);

    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

    // Storing the data in file
    File file = new File(folder, "file01.txt");

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fileOutputStream);
        out.writeObject(arrayList);
        out.close();
        fileOutputStream.close();

        Toast.makeText(context, "sb ho gaya...", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(context, "kuch nahi hua...", Toast.LENGTH_SHORT).show();
    }

}

I am calling this function in my save btn...

storeFile(getApplicationContext(), arrayList);
1

There are 1 best solutions below

0
Roger Lindsjö On

You are asking to write an object (ArrayList), not just the contained strings.

Try something like this

    try (PrintWriter writer = new PrintWriter(file, StandardCharsets.UTF_8)) {
        for (String line: arrayList) {
            writer.println(line);
        }
    }

Depending on the amount of data you might instead use a buffered stream (the above flushes for each line).