Frage

Is there an easy way to write a queue to a file in Java so it can be read back?

My programme currently saves arrays to a properties file in comma delimited format. This is easy, as the array can be iterated over.

My programme also features queues. Is my only option with a queue, to remove every item from the queue and re-add them whenever I want to write all the elements of the queue to file?

What is the easiest way of implementing this?

I ideally want to save the information in the same properties file my other arrays are written to.

War es hilfreich?

Lösung

You could try something like this:

FileOutputStream fos = null;
ObjectOutputStream os = null;

try {
    fos = new FileOutputStream(YOUR_FILE_NAME);
    os = new ObjectOutputStream(fos);

    for(YourObjectType current : YourQueue){
        os.writeXXX(current);  //Where XXX is the appropriate write method depending on your data type
        os.writeChars(",");  //Since you mentioned wanting a comma delimiter..
    }
} catch(IOException e){
   e.printStackTrace(); 
} finally {
    if(fos != null) fos.close();
    if(os != null) os.close();
}

Andere Tipps

The simplest solution is to write the queue as a single collection.

public static void write(String filename, Collection queue) throws IOException {
    try(ObjectOutputStream oos = new ObjectObjectStream(new FileOutputStream(filename))) {
        oos.writeObject(queue);
    }
}

to read this

public static void read(String filename, Collection toAddTo) throws IOException, ClassNotFoundException {
    try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
        toAddTo.addAll((Collection) ois.readObject());
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top