我试图将 (Lieu) 对象放入 anArrayList
但在代码末尾,我的列表仍然是空的。我一直在网上寻找答案,但我发现的只是“将您的对象写入集合然后阅读集合”。但是该文件已经写入,我需要找到一种方法将所有(Lieu)对象放入 ArrayList 中。
这是编写代码(我无法修改):
public static void main(String[] args) {
Lieu<Double, String> p1;
Lieu<Double, String> p2;
Lieu<Double, String> p3;
SegmentGeo<String> e1;
SegmentGeo<String> e2;
SegmentGeo<String> e3;
Parcelle<String> p = new Parcelle<String>();
ArrayList<Mesure<Point<Double>, String>> segs;
p1 = new Lieu<Double, String>(45.573715, -73.900295, "p1");
p2 = new Lieu<Double, String>(45.573882, -73.899748, "p2");
p3 = new Lieu<Double, String>(45.574438, -73.900099, "p3");
e1 = new SegmentGeo<String>(p1, p2, "Parcelle test");
e2 = new SegmentGeo<String>(p2, p3, "Parcelle test");
e3 = new SegmentGeo<String>(p3, p1, "Parcelle test");
segs = new ArrayList<Mesure<Point<Double>, String>>();
segs.add(e1);
segs.add(e2);
segs.add(e3);
try {
p.setMesures(segs);
} catch (TrajectoireNonValideException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ObjectOutputStream ois = null;
try {
ois = new ObjectOutputStream(new FileOutputStream("essai.txt"));
ois.writeObject(p.informationCumulee());
ois.writeObject(p1);
ois.writeObject(p2);
ois.writeObject(p3);
} catch (EOFException ex) {
System.out.println("Fin de fichier atteinte.");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
这就是我想要做的:
public void actionPerformed(ActionEvent arg0) {
JFileChooser chooser = new JFileChooser();
int retour = chooser.showOpenDialog(getParent());
if(retour==JFileChooser.APPROVE_OPTION){
try{
FileInputStream fis = new FileInputStream(chooser.getSelectedFile().getName());
ObjectInputStream ois = new ObjectInputStream(fis);
champNom.setText((String) ois.readObject());//that's just to display the name
while (ois.available()!=0)
{
temp = (Lieu)ois.readObject();
l.add(temp);
}
ois.close();
System.out.print(l.size());//The size is 0
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}