简体   繁体   English

无法在Java中使用DataOutputStream写入整数

[英]Can't write integers with DataOutputStream in Java

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. 此堆对象在Attributes数组中有1000个项目。 However, when I write the data, all I see in the file when I open it in vi is: ^@^@^Cè^@^@^Cé . 但是,当我写入数据时,在vi中打开该文件时所看到的只是: ^@^@^Cè^@^@^Cé A hex editor only shows me 00 00 03 E8 00 00 03 E9 . 十六进制编辑器仅显示00 00 03 E8 00 00 03 E9 So what am I doing wrong? 那我在做什么错?

Output of java -version : 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)

writeInt and writeDouble write binary data to the stream. writeIntwriteDouble将二进制数据写入流。 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 . 如果是这样,请使用writeUTF而不是writeIntwriteDouble

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM