Search code examples
javafileinputstream

read(byte[] b, int off, int len) : Reading A File To Its End


PREMISE

I am new to working with steams in Java and am finding that my question at least appears different from those asked, previously. Here is a fragment of my code at this juncture (the code is more of a proof of concept):

try {
    //file is initialized to the path contained in the command-line args.
    File file = new File(args[0]);
    inputStream = new FileInputStream(file);
    byte[] byteArray = new byte[(int)file.length()];
    int offset = 0;

    while (inputStream.read(byteArray, offset, byteArray.length - offset) != -1) {
        for (int i = 0; i < byteArray.length; i++) {
            if (byteArray[offset + i] >=32 && byteArray[offset + i] <= 126) { 
                System.out.print("#");
            } else {
               System.out.print("@");
            }

        //offset = byteArray.length - offset;
    }
}

GOAL

Here is my goal: to create a program that reads in only 80 bytes of input (the number is arbitrary - let it be x), decides whether each byte within that segment represents an ASCII character, and prints accordingly. The last two portions of the code are "correct" for all intents and purposes: being that the code already appropriately makes the determination and prints, accordingly - this is not the premise of my question.

Let's say the length() of file is greater than 80 bytes and I want - while only reading in 80 bytes of input at a time - to reach the EOF, i.e input the file's entire contents. Each line printed to the console can only contain 80 - or, x amount of - bytes worth of content. I know to adjust the offset and have been tinkering with that; however, when I hit the EOF, I don't want to program to crash and burn - to "explode", so to speak.

QUESTION

When encountering EOF, how do I ensure the captured bytes are still read and that the code in the for loop is still executed?

For instance, changing the above inputStream.read() to:

inputStream.read(byteArray, offset, 80)

This would "bomb" were the end of file (EOF) encountered in reading the last bytes within the file. For instance, if I am trying to read 80 bytes and only 10 remain.


Solution

  • The return value from read tells you the number of bytes which were read. This will be <= the value of length. Just because the file is larger than length does not mean that a request for length number of bytes will actually result in that many bytes being read into your byte[].

    When -1 is returned, that does indicate EOF. It also indicates that no data was read into your byte[].