[英]Saving an ArrayList<ArrayList<Integer>> to File
I am able to save an ArrayList to a file without any problems, but when I try to write and read an ArrayList<ArrayList<Integer>>
to file it nulls out the values.我可以毫无问题地将 ArrayList 保存到文件中,但是当我尝试写入和读取
ArrayList<ArrayList<Integer>>
来归档时,它会将值归零。
I cannot find an example of this format working, or any subject matter as to why it wouldn't work.我找不到这种格式有效的示例,或者任何关于它为什么不起作用的主题。
Does anyone have any insight into why this might happen, or should I just refactor into a HashMap of ArrayList to read/write?有没有人知道为什么会发生这种情况,或者我应该重构为 ArrayList 的 HashMap 来读/写?
public class SaveTest{
public static void SavePoint(ArrayList<ArrayList<Integer>> numbers) throws IOException {
FolderCreator.createFolder();
ObjectOutputStream ousT = new ObjectOutputStream(new FileOutputStream(filePathT));
try{
for (Object x : numbers) {
if(x!=null) {
ousT.writeObject(x); //----not writing data correctly
}
}
ousT.flush();
ousT.close();
}catch(Exception e){e.printStackTrace();}
}
public static ArrayList<ArrayList<Integer>> LoadPoint() throws IOException{
ArrayList<ArrayList<Integer>> tempT = new ArrayList<>();
try (ObjectInputStream oisT = new ObjectInputStream(new FileInputStream(filePathT))){
try {
while (true){
ArrayList<Integer> list = (ArrayList<Integer>)oisT.readObject();
if (list != null){
if (!tempT.contains(list)){ //gets this far and loads null arraylists
tempT.add(list);
}
}else{System.out.println("Null at load");}//----------------------------
}
}catch(EOFException e){}
catch (ClassNotFoundException c){System.out.println("Class not found");}
oisT.close();
return tempT;
}
}
public static void main(String[] args){
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
ArrayList<Integer> nums1 = new ArrayList<>();
ArrayList<Integer> nums2 = new ArrayList<>();
ArrayList<Integer> nums3 = new ArrayList<>();
for(int i=0; i<5; i++){
nums1.add(i);
nums2.add(i);
nums3.add(i);
}
lists.add(nums1);
lists.add(nums2);
lists.add(nums3);
SavePoint(lists);
ArrayList<ArrayList<Integer>> listsReturn = LoadPoint();
for(ArrayList<Integer> list : listReturn){
for(int n : list){
System.out.print("Next number: " + n);
}
}
}
}
In LoadPoint, your.tempT.contains(list) is failing, In other words, it loads list [0,1,2,3,4], and then in the next iteration of the loop, it thinks that tempT already contains [0,1,2,3.4] so doesn't add it again.在 LoadPoint 中,your.tempT.contains(list) 失败了,也就是说,它加载了 list [0,1,2,3,4],然后在循环的下一次迭代中,它认为 tempT 已经包含 [ 0,1,2,3.4] 所以不再添加。
If you take out the "contains" test, it works.如果您取出“包含”测试,它会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.