I'm Java beginner. I have to write some objects in binary file and than be able to write next object at the end of file and in second case in chronogical order. My code right is looks like this:
class Czas implements Serializable {
private int rok;
private int miesiac;
private int dzien;
private int godzina;
private int minuta;
public Czas(int rok, int miesiac, int dzien, int godzina, int minuta) {
this.rok = rok;
this.miesiac = miesiac;
this.dzien = dzien;
this.godzina = godzina;
this.minuta = minuta;
}
public int getRok() {
return rok;
}
public int getMiesiac() {
return miesiac;
}
public int getDzien() {
return dzien;
}
public int getGodzina() {
return godzina;
}
public int getMinuta() {
return minuta;
}
}
class Pomiar implements Serializable /*,Comparable<Pomiar>*/ {
private Czas czas;
private double temperatura;
public Pomiar (Czas czas, double temperatura) {
this.czas = czas;
this.temperatura = temperatura;
}
public void Zapisz(ObjectOutputStream fout) throws IOException{
fout.writeObject(this);
}
public void ZapisChrono(ObjectOutputStream fout) throws IOException {
}
public String toString() {
return "Temperatura: " + temperatura;
}
}
public class AlgorytmyZ3V3 {
public static void main(String[] args) {
try (ObjectOutputStream fout = new ObjectOutputStream(new FileOutputStream(
"BazaPomiarow.dat")))
{
Czas czas1 = new Czas(1988, 6, 15, 10, 18);
Czas czas2 = new Czas(1980, 1, 28, 15, 20);
Czas czas3 = new Czas(1980, 12, 9, 3, 4);
Pomiar p1 = new Pomiar(czas1, 30);
Pomiar p2 = new Pomiar(czas2, 20);
Pomiar p3 = new Pomiar(czas3, 30);
p1.Zapisz(fout);
p2.Zapisz(fout);
p3.Zapisz(fout);
}
catch (IOException e) {
System.out.println("Błąd wejścia/wyjścia.");
}
try {
ObjectInputStream fin = new ObjectInputStream(new FileInputStream("BazaPomiarow.dat"));
ArrayList<Pomiar> lista = new ArrayList();
}
catch(Exception e) {
System.out.println("Wyjątek w czasie deserializacji: " + e);
}
}
}
So I can write next object using method Zapisz, and it will be written at the end of file. But I have problem with chronogical order. I would like to read records from file to ArrayList and then sort that list and add next object with specific index and at last write whole ArrayList again to file. That's how I would like to do this and that's why I need to know how to read those objects from file and write to ArrayList. Maybe it's not the best way, but it's school task and I need to be as acurate as it's possible.
sry for names in Polish, but I think it's not a problem here as I only need to know, how to use specific thing in Java.