Reputation: 813
I know this has been asked many times, but I've tried everyone's suggested code and I can't make it work on my system.
public class Heap implements Serializable {
public Attribute[] A; // Array of data, has elements name/String, p1/int, n1/int, ig/double
private int n = 0; // num elements
private int max = 0; // Max elements
...
}
public void serialize(Heap hp, String filename) throws IOException {
DataOutputStream dst = new DataOutputStream(new FileOutputStream(filename));
dst.writeInt(hp.heapMax());
dst.writeInt(hp.A.length);
System.out.println("Writing heap max " + hp.heapMax() + " and heap size " + hp.A.length);
for(int i = hp.A.length - 1; i > 0; i--) {
dst.writeInt(hp.A[i].n1);
dst.writeInt(hp.A[i].p1);
dst.writeDouble(hp.A[i].ig);
dst.writeUTF(hp.A[i].name);
}
dst.close();
}
This Heap object has 1000 items in the Attributes array. However, when I write the data, all I see in the file when I open it in vi is: ^@^@^Cè^@^@^Cé
. A hex editor only shows me 00 00 03 E8 00 00 03 E9
. So what am I doing wrong?
Output of java -version
:
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
Upvotes: 0
Views: 247
Reputation: 6947
writeInt
and writeDouble
write binary data to the stream. You are seeing the correct values. Since you think you are doing something wrong, I'm guessing you expected to see string values? If so, use writeUTF
instead of writeInt
and writeDouble
.
Upvotes: 3