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]);
            }
3
  • Please can you post the code that is producing that result. Commented Jan 4, 2015 at 20:21
  • Try System.out.println(b[i]) instead. That will start a new line for each number. Is that what you want? Commented Jan 4, 2015 at 20:24
  • The file that I'm reading is a text file with words in it. Hence, I expect some words to be written to the console. I dont understand why these numbers are being printed Commented Jan 4, 2015 at 20:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.