如何在Android App中将ArrayList写入文本文件

问题描述 投票:0回答:1

因此,我拥有该应用程序所需的一些数据的ArrayList,并且从名为MyData.txt的文本文件中加载数据并将其存储在ArrayList中也没有任何问题。但是问题是,在用户对已加载的ArrayList中存储的数据进行了某些更改之后,我希望使用新的ArrayList更新存储在MyData.txt中的数据。我为此编写了一些代码,但是它似乎不起作用,并且在我按保存按钮后我的txt文件没有得到更新,它只是跳出了应用程序。

 public void SaveData(List<Four> list) throws IOException {
    FileOutputStream file = openFileOutput("MyData.txt", MODE_PRIVATE);
    OutputStreamWriter outputFile = new OutputStreamWriter(file);
    for(int i=0 ; i<list.size() ; i++){
        outputFile.write(list.get(i).first+";"+list.get(i).second+";"+list.get(i).second+";"+list.get(i).fourth+"\n");
    }
    outputFile.flush();
    outputFile.close();
}

我有一个ArrayList,其数据类型为Four(四是一个类,其中包括“ String(显示为第一个,String(显示为第二,int(显示为第三个),int(显示为第四个)))代码的输出应存储在一个文本文件中,例如,如果“我的列表”只有一个索引,例如“ John Brown 1938494 0”,则我的文本文件应类似于“ John; Brown; 1938494; 0”。

如果您需要了解有关代码的其他信息,请告诉我。谢谢您的时间。

java android text-files
1个回答
0
投票

您可以使用google gson。

    class Four {
    String first,second;
    int third,fourth;
    public Four()
    {

    }
}
 //save_array(your_context,"MyData.txt",your_array)
void save_array(Context contxt,String file_name,ArrayList<Four> testes)
{
    Gson gson = new Gson();
    String json = gson.toJson(testes);
    String root = contxt.getExternalFilesDir(null).getAbsolutePath() + "/arrays";


    File file = new File(root);
    file.mkdirs();
    try {
        File out_file = new File(file, file_name);
        if(out_file.exists()){
            out_file.delete();
        }
        FileWriter writer = new FileWriter(out_file,true);
        writer.append(json);
        writer.flush();
        writer.close();
    }catch (Exception ex)
    {

    }
}
ArrayList<Four> saved_array(Context contxt, String file_name) throws IOException {
    String path = contxt.getExternalFilesDir(null).getAbsolutePath() + "/arrays/"+file_name;


    Gson gson = new Gson();
    BufferedReader br = new BufferedReader(new FileReader(path));
    return gson.fromJson(br, new TypeToken<List<Four>>(){}.getType());


} 

您可以致电为记住要请求存储权限

© www.soinside.com 2019 - 2024. All rights reserved.