简体   繁体   中英

Android - How can I write an ArrayList to a text file line by line and read it back?

I'm very new to Android/Java programming (have some experience in VB and took some C++ classes in college many years ago but don't remember anything), so I apologize for the headache in advance.

I'm using Android Studio and I've worked on this for a couple days now (lots of Google searches) and can't get anything to function the way I want it to. I can write to a text file, can read from the text file but can't get it to write line by line, read line by line or even count how many lines are there to begin with (my initial thought is if I can count how many lines I could do a loop to write/read by line), but I'm just missing it.

I know some of the code is sloppy, I'm learning from pulled examples from all over the web. Currently, it'll create the ArrayList items, display it in the first ListView and write it to a text file, and I can read it back into the second ListView but it's in a single line format that looks like:

[Testing - how are you?, I'm good and you?, Great, thanks!]

Examples on writing/reading line by line that I've found on the web either don't work or rely on 3rd party dependencies which I'd rather not use and figure out how to do it myself. Thank you in advance!

package com.example.thedoctor.readwritearraylists;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayList<String> origitems;
    ArrayList<String> newitems;

    ArrayAdapter<String> origitemsAdapter;
    ArrayAdapter<String> newitemsAdapter;

    ListView lvOrigItems;
    ListView lvNewItems;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvOrigItems = (ListView) findViewById(R.id.lvOriginal);
        lvNewItems = (ListView) findViewById(R.id.lvNew);

        origitems = new ArrayList<String>();
        newitems = new ArrayList<String>();

        origitemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, origitems);
        newitemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, newitems);

        lvOrigItems.setAdapter(origitemsAdapter);
        lvNewItems.setAdapter(newitemsAdapter);

    }

    public void makeArray(View v) {
        origitemsAdapter.add("Testing - how are you?");
        origitemsAdapter.add("I'm good and you?");
        origitemsAdapter.add("Great, thanks!");
        origitemsAdapter.notifyDataSetChanged();
    }

    public void saveItems(View v) {
        String file = "myfile.txt";
        String huh = String.valueOf(origitems);
        try {
            FileOutputStream fileout = openFileOutput(file, MODE_PRIVATE);
            OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
            outputWriter.write(String.valueOf(huh) + System.getProperty("line.separator"));
            outputWriter.close();

            //display file saved message
            Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void readItems(View v) {
        String file = "myfile.txt";
        int READ_BLOCK_SIZE = 100;

        try {
            FileInputStream fileIn = openFileInput(file);
            InputStreamReader InputRead = new InputStreamReader(fileIn);
            char[] inputBuffer = new char[READ_BLOCK_SIZE];
            String s = "";
            int charRead;

            while ((charRead = InputRead.read(inputBuffer)) > 0) {
                // char to string conversion
                String readstring = String.copyValueOf(inputBuffer, 0, charRead);
                s += readstring;
            }
            newitemsAdapter.add(s);
            newitemsAdapter.notifyDataSetChanged();
            InputRead.close();
            Toast.makeText(getBaseContext(), "The file " + file + " has been read from internal storage\n", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Try using an ObjectInputStream instead of an InputStreamReader . Since ArrayList is Serializable, you can deserialize the object itself directly into an ArrayList object. I do it like this:

private ArrayList<String> getSavedArrayList() {
    ArrayList<String> savedArrayList = null;

    try {
        FileInputStream inputStream = openFileInput("your.filename");
        ObjectInputStream in = new ObjectInputStream(inputStream);
        savedArrayList = (ArrayList<String>) in.readObject();
        in.close();
        inputStream.close();

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

    return savedArrayList;
}

Of course this means you'll have to save the ArrayList by serializing your original object using ObjectOutputStream . You can do that like this:

private void saveArrayList(ArrayList<String> arrayList) {
    try {
        FileOutputStream fileOutputStream = openFileOutput("your.filename", Context.MODE_PRIVATE);
        ObjectOutputStream out = new ObjectOutputStream(fileOutputStream);
        out.writeObject(arrayList);
        out.close();
        fileOutputStream.close();

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

For writing an ArrayList to file

  private ArrayList<ModelClass> getSavedArrayList() {
    ArrayList<ModelClass> savedArrayList = null;
    File direct = new File(Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.app_name));
    if (!direct.exists()) {
        direct.mkdirs();
    }

    try {
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(direct + "/girls.html")));
        for (int i = 0; i < params.size(); i++) {
            ModelClass data = params.get(i);
            String links = data.link.toString() + "\n\n";
            dos.writeChars(links);
        }
        dos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return savedArrayList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM