overhauling save and load routines

This commit is contained in:
Stephan Richter
2020-09-21 12:07:10 +02:00
parent 72858b4aba
commit 09a7c9f5b7
10 changed files with 257 additions and 159 deletions

View File

@@ -1,6 +1,8 @@
package de.srsoftware.web4rail.moving;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
@@ -13,7 +15,7 @@ public class Car {
private static final String ID = "id";
private static final String NAME = "name";
private static final String LENGTH = "length";
private static HashMap<String,Car> cars = new HashMap<String, Car>();
static HashMap<String,Car> cars = new HashMap<String, Car>();
public int length;
private String name;
private String id;
@@ -24,10 +26,28 @@ public class Car {
public Car(String name, String id) {
this.name = name;
this.id = id == null ? ""+new Date().getTime() : id;
cars.put(this.id, this);
if (id == null) {
try { // make sure multiple consecutive creations get different ids
Thread.sleep(1);
} catch (InterruptedException e) {}
id = ""+new Date().getTime();
}
this.id = id;
cars.put(id, this);
}
public static Car get(String nameOrId) {
HashMap<String, Car> cs = cars;
Car car = cars.get(nameOrId);
if (car == null) {
for (Car c : cars.values()) {
if (c.name.equals(nameOrId)) car = c;
}
}
return car;
}
public String id() {
return id;
}
@@ -44,10 +64,32 @@ public class Car {
return name;
}
public static void loadAll(String filename) throws IOException {
cars.clear();
BufferedReader file = new BufferedReader(new FileReader(filename));
String line = file.readLine();
while (line != null) {
JSONObject json = new JSONObject(line);
String name = json.getString(Car.NAME);
String id = json.getString(Car.ID);
Car car = json.has(Locomotive.LOCOMOTIVE) ? new Locomotive(name, id) : new Car(name,id);
car.load(json);
line = file.readLine();
}
file.close();
}
protected void load(JSONObject json) {
if (json.has(ID)) id = json.getString(ID);
if (json.has(LENGTH)) length = json.getInt(LENGTH);
}
public static void saveAll(String filename) throws IOException {
BufferedWriter file = new BufferedWriter(new FileWriter(filename));
for (Entry<String, Car> entry: cars.entrySet()) {
file.write(entry.getValue().json()+"\n");
Car c = entry.getValue();
file.write(c.json()+"\n");
}
file.close();
}