Writing a list to a file

我只是一个虾纸丫 提交于 2021-02-10 08:45:17

问题


I'm trying to store all elements in a List in a file for later retrieval so when the program closes that data isn't lost. Is this possible? I've written some code to try, but it's not what I want. This is what I have written so far though.

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

Suggestions?

Edit: I'm looking for the array itself to be written in the file, but this is what is writing. enter image description here


回答1:


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

I edited the bw.write line to change the int to a string before writing it.




回答2:


If you want it to write the actual number, use a PrintWriter instead.

PrintWriter pw = new PrintWriter(new File(...));
pw.print(aList.get(i));



回答3:


Just learnt a clean solution for this. Using FileUtils of apache commons-io.

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

change false to true, if you want to append to file, in case it exists already.



来源:https://stackoverflow.com/questions/13597373/writing-a-list-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!