在 RandomAccessFile .csv 中阅读短裤

Reading in shorts in a RandomAccessFile .csv

我正在尝试读取文件开头有 3 个短裤的 .csv 文件。我需要读入它们并设置为一个变量,但它似乎没有提取正确的数据。

private short M = 0;
private short rootPtr = 0;
private short N = 0;
RandomAccessFile file;
private short[] TP; // array of TPs for one node
private String[] KV; // array of KVs for one node
private short[] DRP; // array of DRPs for one node
private int nodesRead; // iterator for nodes read
private int sizeOfDataRec; // stores size of data record: (M - 1) * (7) + 2

    // sets values from header record
    file.seek(0);
    M = file.readShort();
    rootPtr = file.readShort();
    N = file.readShort();
    sizeOfDataRec = (M - 1) * (7) + 2; // sets size of data record
    TP = new short[M];
    KV = new String[M - 1];
    DRP = new short[M - 1];

文件的前 3 个短裤应该是 05、11、22,但是当我在该位末尾打印出 M 时得到 12344

CSV 文件是文本文件。它不包含短裤,您不能指望在上面使用 RandomAccessFile.readShort()。更有可能你应该使用 Scanner.nextShort()

来自 RandomAccessFile#readShort

的 Java 文档

Reads a signed 16-bit number from this file. The method reads two bytes from this file, starting at the current file pointer. If the two bytes read, in order, are b1 and b2, where each of the two values is between 0 and 255, inclusive, then the result is equal to:

(short)((b1 << 8) | b2)

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown

现在让我们看看你的情况发生了什么,假设你正在阅读的第一个短值是 05

readShort 读取两个字节时,它会将 0 读取为 48,将 5 读取为 53(记住 ASCII 码),然后将上面提到的公式应用于它,得到

(48 << 8) | 53 = 12288 + 53 = 12341

所以您在短变量中看到了这些值。

您应该按照 EJP 的建议使用 Scanner#nextShort