Android - 如何逐行将ArrayList写入文本文件并将其读回?

时间:2016-04-20 14:15:48

标签: java android arraylist

我对Android / Java编程非常陌生(在VB中有一些经验并且在很多年前在大学里学过一些C ++课程但是没有记住任何东西),所以我提前为此头痛道歉。

我正在使用Android Studio,而且我已经对此工作了几天(很多Google搜索)并且无法按照我想要的方式运行任何功能。我可以写一个文本文件,可以从文本文件中读取,但不能让它逐行写入,逐行读取,甚至计算开始的行数(我最初的想法是,如果我可以数我可以循环写入/读取多少行,但我只是错过了它。

我知道有些代码很草率,我正在学习来自网络上的各种示例。目前,它将创建ArrayList项,将其显示在第一个ListView中并将其写入文本文件,然后我可以将其读回到第二个ListView中,但它采用单行格式,如下所示:

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

我在网上找到的逐行编写/阅读的示例要么不起作用,要么依赖我不想使用的第三方依赖项,并弄清楚如何自己动手。提前谢谢!

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();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

尝试使用ObjectInputStream代替InputStreamReader。由于ArrayList是Serializable,因此您可以将对象本身直接反序列化为ArrayList对象。我是这样做的:

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;
}

当然,这意味着您必须使用ObjectOutputStream序列化原始对象来保存ArrayList。你可以这样做:

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();
    }
}

答案 1 :(得分:0)

用于将ArrayList写入文件

  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;
}