ObjectOutputStream i ObjectInputStream problem

0

Mam dwie klasy Student i Main. Program pozwala tworzyć nowych studentów ale gdy chcę zapisać ich do pliku i następnie odczytać nie wyskakuje żaden błąd ale nic się nie dzieje. Pomoże mi ktoś dojść do tego w czym tkwi problem? :)

public class Main implements Serializable{
	
	ObjectOutputStream plik = null;

	public static void main(String[] args) throws IOException, ClassNotFoundException
	{
		SortedSet<Student> studenci = new TreeSet<Student>();
		Scanner sc = new Scanner(System.in);
		
		for(int k=1; k<=2; k++)
		{
			System.out.println("Podaj nazwisko i imię:");
			
			String nazwisko = sc.next();
			String imie = sc.next();
			
			System.out.println("Podaj album, rok i średnią:");
			
			long album = sc.nextLong();
			int rok = sc.nextInt();
			double srednia = sc.nextDouble();
			
			Student nowy = new Student(nazwisko, imie, album, rok, srednia);
			
			studenci.add(nowy);
			
		}
                sc.close(); 
		
		Main m = new Main();
		m.save("studenci.ser");
		m = m.restore("studenci.ser");
			
			
	}
	
	 public void save(String nazwa) throws IOException
	{
		try{
			ObjectOutputStream plik = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(nazwa)));
			plik.writeObject(this);
			plik.close();
		}
		
		catch(IOException e) {
			System.out.println("IOException w save() " + e.getMessage());
		}
		
	}
	 
	
	 public Main restore(String nazwa) throws IOException, ClassNotFoundException
	{
			ObjectInputStream plik = new ObjectInputStream(new BufferedInputStream(new FileInputStream(nazwa)));
		        Main tmp=(Main)plik.readObject();
			plik.close();	
			return tmp;
	} 

	
}
1

Ale Ty nie zapisujesz informacji o utworzonych studentach.

                Main m = new Main();
                m.save("studenci.ser");

Tworzysz nowy obiekt typu Main, w którym lista studentów jest pusta i ten obiekt zapisujesz.
Serializacja zapisuje pola w klasie, a Ty, jak napisał @Kerai, przechowujesz informacje o studentach w zmiennej lokalnej metody main. Zmienne lokalne nigdy nie są zapisywane.

1 użytkowników online, w tym zalogowanych: 0, gości: 1