将数组列表<数组列表<Integer>>保存到文件



我可以毫无问题地将ArrayList保存到文件中,但当我尝试写入和读取ArrayList<ArrayList<Integer>>文件时,它会清空值
我找不到这种格式有效的例子,也找不到任何关于它为什么不起作用的主题。

有人知道为什么会发生这种情况吗?或者我应该重构到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){
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);
}
}
}
}

在LoadPoint中,您的!tempT.contains(list(失败。换句话说,它加载列表[0,1,2,3,4],然后在循环的下一次迭代中,它认为tempT已经包含[0,1,21,3,4],所以不再添加它。

如果你把";包含";测试,它工作。

最新更新