Search code examples
javaseekrandomaccessfile

Java RandomAccessFile how to Read nth byte as a character


I was learning java fileoperations, and I was trying to read nth byte as character in a text file. I used RandomAccessFile (I am not sure if this is the right module to use here), and my code is

import java.io.RandomAccessFile;
public class testclass {

public static void main(String[] args) throws IOException {
    RandomAccessFile f = new RandomAccessFile("temptext.txt", "r");
    f.seek(200);
    System.out.println(f.readChar());
    }
}

This is printing some unknown characters, which is not mentioned in the text file. What am I doing wrong here? My final aim is to reverse the entire text in the text file using a forloop, if I can get this right.


Solution

  • Check this JavaDoc:

    public final char readChar() throws IOException

    Reads a character from this file. This method reads two bytes from the file, >starting at the current file pointer. If the bytes read, in order, are b1 >and b2, where 0 <= b1, b2 <= 255, then the result is equal to: (char)((b1 << 8) | b2)

    So for your example to work, you shoud use readByte() instead.