2

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.

scott
  • 1,557
  • 3
  • 15
  • 31
  • 1
    Bytes and chars don't always align (for utf-8 for instance). What charset do you have in textfile? – Jan Dec 06 '15 at 19:09
  • @Jan it is the default ascii text in linux with linux style line terminators. It was created with a vi. – scott Dec 06 '15 at 19:52

1 Answers1

3

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.

Jan
  • 13,738
  • 3
  • 30
  • 55
  • Thank you Jan. After this, I could see that the returned value is the ASCII value of the character. – scott Dec 07 '15 at 06:39