Liste speichern. Was lässt sich verbessern?

handshake45

Bekanntes Mitglied
Java:
class El {
	String schema;
	JSONObject header;
	JSONObject message;

	El(String schema, JSONObject header, JSONObject message) {
		this.schema = schema;
		this.header = header;
		this.message = message;
	}
}


	private static final LinkedList<El> list = new LinkedList<El>();

	public static void saveList1() {
		try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list1data.txt"))) {
			oos.writeInt(list.size());
			for (El el : list) {
				oos.writeObject(new String[] { el.schema, el.header.toString(), el.message.toString() });
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void loadList1() {
		if (new File("list1data.txt").exists()) {
			try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list1data.txt"))) {
				int size = ois.readInt();
				for (int i = 0; i < size; i++) {
					String[] s = (String[]) ois.readObject();
					list.add(new El(s[0], new JSONObject(s[1]), new JSONObject(s[2])));
				}
			} catch (IOException | ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

Ich denke das ist zu kompliziert, übersehe ich etwas?
 
Beispiel für das Speichern als JSON:
Java:
        Artist artist = new Artist();
        artist.setId(1L);
        artist.setName("The Beatles");

        ObjectMapper mapper = new ObjectMapper();

        File file = new File("artist.json");
        try {
            // Serialize Java object info JSON file.
            mapper.writeValue(file, artist);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Deserialize JSON file into Java object.
            Artist newArtist = mapper.readValue(file, Artist.class);
            System.out.println("newArtist.getId() = " + newArtist.getId());
            System.out.println("newArtist.getName() = " + newArtist.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
Maven:
XML:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>LATEST</version>
</dependency>
 
Das geht mit Sicherheit auch zu Fuß, wenn du eh JSonObject drin hast. Fände ich immer noch besser als die elendige Serialisierung. Die ist für mich nur ein Notbehelf.
 
Zuletzt bearbeitet:

Neue Themen


Zurück
Oben