import java.util.Vector;
import java.io.*;
public class Queue extends Vector {
/*
** FIFO, first in first out
*/
Queue() {
super();
}
void put(Object o) {
addElement(o);
}
Object get() {
if (isEmpty()) return null;
Object o = firstElement();
removeElement(o);
return o;
}
Object peek() {
if (isEmpty()) return null;
return firstElement();
}
}
To serialize (save the Queue state to a file) :
public static void main(String args[]) {
Queue theQueue;
theQueue = new Queue();
theQueue.put(new int[]{1, 2, 3, 4});
theQueue.put("ABCDE");
theQueue.put(new Integer(3));
System.out.println(theQueue.toString());
// serialize the Queue
System.out.println("serializing theQueue");
try {
FileOutputStream fout = new FileOutputStream("thequeue.dat");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(theQueue);
oos.close();
}
catch (Exception e) { e.printStackTrace(); }
}
To unserialize (to load a previously saved Queue) :
public static void main(String args[]) {
Queue theQueue;
theQueue = new Queue();
// unserialize the Queue
System.out.println("unserializing theQueue");
try {
FileInputStream fin = new FileInputStream("thequeue.dat");
ObjectInputStream ois = new ObjectInputStream(fin);
theQueue = (Queue) ois.readObject();
ois.close();
}
catch (Exception e) { e.printStackTrace(); }
System.out.println(theQueue.toString());
}
hope that helps
> build a string with your array
>
Then you'll have to loop over all elements and write each int as a String to a file. If you ever want to read the data back, you'll have to parse all those Strings back to int's again.
@OP:
If it's only for displaying purpose, and you need not read the data back, you can do it as calvino_ind suggested or, if you need the values at a later stage back in your program, try serialization.
> ...
> hope that helps
No need for wrappers or collection classes. You can just serialize arrays of primitives.
Example:
// Write to disc:
String fileName = "test.ser";
int[] array = {6,6,6};
System.out.println(java.util.Arrays.toString(array));
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(array);
out.close();
} catch(IOException ex) {
ex.printStackTrace();
}
// And to read it back:
int[] anotherArray = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(fileName);
in = new ObjectInputStream(fis);
anotherArray = (int[])in.readObject();
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
System.out.println(java.util.Arrays.toString(anotherArray));