问题
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.
回答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