我编写了应保存对象ArrayList的程序,然后读取并添加新索引。从物理上讲,每个新条目都会添加到文件中,但我只能看到runnning后的第一个条目。我不知道。我认为我知道的是我再次编写相同的代码但是在一个类中。
保存:
class Zapis {
private Operacje op = new Operacje();
private GregorianCalendar gregorianCalendar = new GregorianCalendar();
private Scanner scanner = new Scanner(System.in);
private ArrayList<String> x = new ArrayList<String>();
private Odczyt historia = new Odczyt();
public void test() throws IOException, ClassNotFoundException, NullPointerException {
try {
op.dzien = String.format("%tc", gregorianCalendar);
op.kwota = scanner.nextInt();
x.add(op.toString());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("costam.bin",true));
objectOutputStream.writeObject(x);
objectOutputStream.close();
;
} catch (NullPointerException e) {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("costam.bin",true));
op.dzien = String.format("%tc", gregorianCalendar);
op.kwota = scanner.nextInt();
x.add(op.toString());
objectOutputStream.writeObject(x);
objectOutputStream.close();
}
}
读:
public class Odczyt {
public static ArrayList<String> array;
public void test() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("costam.bin"));
array = (ArrayList<String>) objectInputStream.readObject();
int k = array.size();
System.out.println(k);
for (int i = 0; i < k; i++) {
System.out.println(array.get(i));
}
objectInputStream.close();
}
答案 0 :(得分:0)
public class Wszystko {
private static Operacje op = new Operacje();
private static Scanner scanner = new Scanner(System.in);
private static GregorianCalendar gregorianCalendar = new GregorianCalendar();
private static ArrayList<String> array;
public static void test() throws IOException, ClassNotFoundException {
try {
wczytaj();
ustawOp();
dodajDoArray();
wydrukuj();
zapisz();
} catch (FileNotFoundException e) {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("costam.bin"));
op.dzien = String.format("%tc", gregorianCalendar);
op.kwota = scanner.nextInt();
array.add(op.toString());
objectOutputStream.writeObject(array);
objectOutputStream.close();
}
}
public static void wczytaj() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("costam.bin"));
array = (ArrayList<String>) objectInputStream.readObject();
}
public static void ustawOp(){ op.dzien = String.format("%tc", gregorianCalendar);
op.kwota = scanner.nextInt();}
public static void dodajDoArray(){
array.add(op.toString());}
public static void wydrukuj(){
int s = array.size();
for(int i =0; i<s; i++){
System.out.println(array.get(i));
}
}
public static void zapisz() throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("costam.bin",true));
objectOutputStream.writeObject(array);
objectOutputStream.close();}
}
一切正常:D