簡體   English   中英

嘗試讀取二進制保存的整數時,readInt()不起作用

[英]readInt() not work when try read binary saved integer

我試圖保存一些整數,並以二進制格式將其加倍到txt文件。 我認為數字可以正確保存,但是問題是當我嘗試使用readInt()讀取整數時。 例如,當整數值為12時,該整數的程序輸出為208797696,並且具有更多整數的程序始終以EOF異常結束。 readDouble()沒問題,它可以正常工作。

import java.util.Scanner;
import java.io.*;

public class CandyFruit {

public static void main(String[] args) throws IOException {
    int i;
    int int_sc ;
    double double_sc;
    String string_sc;
    int seek_w = 0; //seek for writing

    String map = ""; 
    Scanner scan = new Scanner(System.in);
    try (RandomAccessFile write = new RandomAccessFile("fgh.txt", "rw")) {

    for (;;) {  
        System.out.println("1 - write int, 2 - write double, 0 - break");
        i = scan.nextInt();
        if (i == 0) break;
        System.out.println("Your choice:");
        if (i == 1) {
            int_sc = scan.nextInt();
            write_int(write, int_sc, seek_w);
            map = map + "1";
            seek_w += 4; //seek growth for int

        }
        else if (i == 2) {
            double_sc = scan.nextDouble();
            write_double(write, double_sc, seek_w);
            map = map + "2"; 
            seek_w += 8; //seek growth for double
        }
    }
    }

    //catch

    try (RandomAccessFile read = new RandomAccessFile("fgh.txt", "rw")) {

        int seek_r = 0;

        for (int o = 0; o < map.length(); o++) {
            char c = map.charAt(o);

            if (c == '1') {
                read_int(read, seek_r);
                seek_r += 4; //seek growth for int

            }
            else if (c == '2') {

                read_double(read, seek_r);
                seek_r += 8; //seek growth for double 
            }


        }
    }

    //catch

}

public static void write_int (RandomAccessFile write, int scanned, int s) throws IOException {
    write.seek(s);
    write.write(scanned);
}

public static void write_double(RandomAccessFile write, double scanned, int s) throws IOException {
    write.seek(s);
    write.writeDouble(scanned);
}

public static void read_int(RandomAccessFile read, int s) throws IOException {
    read.seek(s);
    System.out.println("Int is: "+read.readInt());
}

public static void read_double(RandomAccessFile read, int s) throws IOException {
    read.seek(s);
    System.out.println("Double is: "+read.readDouble());
}

}

您的write_int方法使用RandomAccessFile.write()進行寫入,這會將字節寫入文件。 當使用readInt() ,您將讀取該單個字節以及三個字節的其他任意數據(因為您沒有寫它們)。

您應該在write_int使用RandomAccessFile.writeInt()

暫無
暫無

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

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