簡體   English   中英

無法在Java中使用DataOutputStream寫入整數

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

我知道這個問題已經被問過很多次了,但是我已經嘗試了每個人的建議代碼,但無法在我的系統上使用它。

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();
}

此堆對象在Attributes數組中有1000個項目。 但是,當我寫入數據時,在vi中打開該文件時所看到的只是: ^@^@^Cè^@^@^Cé 十六進制編輯器僅顯示00 00 03 E8 00 00 03 E9 那我在做什么錯?

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)

writeIntwriteDouble將二進制數據寫入流。 您看到的是正確的值。 由於您認為自己做錯了什么,所以我猜您應該看到字符串值? 如果是這樣,請使用writeUTF而不是writeIntwriteDouble

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM