-2

I'm trying to read in a .csv file with 3 shorts in the beginning of the file. I need to read them in and I'm setting to a variable but it seems to not be pulling in the right data.

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];

The first 3 shorts of the file should be 05,11,22 but I get 12344 when I print out M at the end of this bit

  • I suggest using a library for reading CSV file, if you have no constraints. (https://commons.apache.org/proper/commons-csv/) – dumitru Apr 12 '16 at 07:58

2 Answers2

1

A CSV file is text. It doesn't contain shorts, and you can't expect to use RandomAccessFile.readShort() on it. More probably you should be using Scanner.nextShort() etc.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

From Java Docs of RandomAccessFile#readShort

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

Now lets see what is happening in your case, suppose first short value you are reading is 05

when readShort reads two bytes it will read 0 as 48 and 5 as 53 (remember ASCII codes) and then it applies above mentioned formula to it which gives

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

So you are seeing these values in your short variables.

You shall use Scanner#nextShort as suggested by EJP

Sanjeev
  • 9,876
  • 2
  • 22
  • 33