0
char[] input =new char[24];
        for (int i=0; i<24; i++){
            input[i] = (char)('a'+i);
        }
        RandomAccessFile bf = new RandomAccessFile("data1.txt", "rw");
        for(int i=0; i<24; i++){
            bf.writeChar(input[i]);
        }

With Above code, when I open the file, it seems to be "abcd..." as I expected, but when I try to read the file

RandomAccessFile rf1  = new RandomAccessFile("data1.txt", "r");
   rf1.seek(0);
   System.out.println(rf1.readChar());
   rf1.seek(1);
   System.out.println(rf1.readChar());

    rf1.close();

It gives 'a' as expected but when seek(1) it gives me ? rather than b, why?

user3495562
  • 335
  • 1
  • 4
  • 16

2 Answers2

1

A char is 16 bits, i.e. 2 bytes. You're reading from the middle of the first character, which results in an unmappable unicode character (which is translated to '?'). You want to do seek(2) instead.

From the javadoc for public final void writeChar(int v):

Writes a char to the file as a two-byte value, high byte first. The write starts at the current position of the file pointer.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Sorry, I thought Char is 1 byte.....Also, is there a function like sizeof in C such that I could not make such mistakes – user3495562 Apr 09 '14 at 19:23
  • It depends on the encoding. RandomAccessFile's writeChar() writes it as a 2 byte unicode character. Always pay attention to the encoding when reading and writing text. – Kayaman Apr 09 '14 at 19:24
  • @user3495562 To clarify: You should not be using `char` to read/write text from a file unless you *really* understand what that's doing. Character set encoding is important in modern software. – Brian Roach Apr 09 '14 at 19:32
  • @BrianRoach hi, Then what should I do, say if I want to use filechannel to input an integer, how many bytes should I allocate? – user3495562 Apr 09 '14 at 19:36
  • If you're reading/writing binary data, it shouldn't be as bytes that map to a character set. Read/write it as 4 bytes (which is the size of an `int` in Java) – Brian Roach Apr 09 '14 at 19:38
0

RandomAccessFile's readChar and writeChar methods reads/writes Unicode (2-byte) codepoint.

seek method positions file access pointer as offset in bytes, so seek(1) places read pointer on the second byte of Unicode "a" and following readChar retrieves a Unicode character constructed from low-byte of "a" and high-byte of "b"

cit
  • 1