0

I'm trying to implement the tail program and want to print the last n bytes of a file. I've used a RandomAccessFile variable to store the data from the text file. When I try to retrieve the data and print it to the console, I'm getting something like this:

-n1
65109710979710979710810979710810510510979710910659711010510979711410011897114107109797114100119111108102106597114111110

How does on properly retrieve the data from the byte array?

This is my code:

RandomAccessFile raf = new RandomAccessFile(file, "r");
            byte[] b = new byte[n];
            raf.readFully(b, 0, n);
            for (int i = 0; i < n; i++) {
                System.out.print(b[i]);
            }
Adway Dhillon
  • 77
  • 1
  • 4
  • 16

1 Answers1

3

You are printing the byte value. To convert e.g. an array of bytes to a String that you can print on System.out.println try the following:

System.out.println(new String(b));

If you wish to convert each byte (as in your loop) to a printable charyou can do the following conversion:

for (int i = 0; i < 10; i++) {
    char c = (char) (b[i] & 0xFF);
    System.out.print(c);
}

A byte is simply one byte in size (8 bits) whereas a char in Java i 16 bits (2 bytes). Therefore the printed bytes does not make sense, it is not an entire character.

See this link for more info.

Community
  • 1
  • 1
wassgren
  • 18,651
  • 6
  • 63
  • 77