将列表写入文件

3
我正在尝试将列表中的所有元素存储在文件中,以便稍后检索,以避免程序关闭时数据丢失。这是否可行?我尝试编写了一些代码,但它不是我想要的。以下是迄今为止我写的代码。
import java.util.*;
import java.io.*;
public class Launch {
    public static void main(String[] args) throws IOException {
        int[] anArray = {5, 16, 13, 1, 72};
        List<Integer> aList = new ArrayList();
        for (int i = 0; i < anArray.length; i++) {
            aList.add(anArray[i]);
        }
        File file = new File("./Storage.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < aList.size(); i++) {
            bw.write(aList.get(i));
        }
        bw.flush();
        bw.close();
    }
}

建议是什么?
编辑:我希望将数组本身写入文件,但这是正在写入的内容。 enter image description here

3
“it's not what I want”的翻译是“这不是我想要的”,询问对方“what you want?”即“你想要什么?” - Abubakkar
请阅读帖子的末尾,我刚刚编辑了它。 - Dan
3个回答

4
import java.util.*;
import java.io.*;
public class Launch {
    public static void main(String[] args) throws IOException {
        int[] anArray = {5, 16, 13, 1, 72};
        List<Integer> aList = new ArrayList();
        for (int i = 0; i < anArray.length; i++) {
            aList.add(anArray[i]);
        }
        File file = new File("./Storage.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < aList.size(); i++) {
            bw.write(aList.get(i).toString());
        }
        bw.flush();
        bw.close();
    }
}

我将bw.write的代码行更改为在写入之前将int转换为字符串。

1

我刚学会了一种干净的解决方法。使用apache commons-io中的FileUtils

File file = new File("./Storage.txt");
FileUtils.writeLines(file, aList, false);

如果您想将内容追加到文件中(如果文件已经存在),请将false更改为true。


0
如果你想要输出实际的数字,请使用PrintWriter
PrintWriter pw = new PrintWriter(new File(...));
pw.print(aList.get(i));

或者你仍然可以使用BufferedWriter,只需在列表项上使用 toString(),就像下面 @nair.ashvin 建议的那样。 - Isaac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接