Luca
Luca

Reputation: 1776

file input stream odd behaviour

I have the following simple code that reads from a file in the current directory into a byte array and the prints the contents of the array (which is the contents of the file, ASCII printable characters from ASCII 32 to ASCII 126):

import java.io.FileInputStream;
import java.io.IOException;

class Input {

  public static void main(String[] args) throws IOException {
    FileInputStream fis=null;
    try {
      fis=new FileInputStream("file.txt");
      int available=fis.available();
      byte[] read=new byte[available];
      int bytesRead;
      int offset=0;
      while(offset<read.length) {
        bytesRead=fis.read(read,offset,read.length-offset);
        if (bytesRead==-1) break;
        offset+=bytesRead;
      }
      System.out.println(read.length);
      for (byte b:read) {
        int i=b & 0xFF;
        System.out.write(i);
        System.out.write('\t');
      }
    }
    finally {
      if (fis != null)
        try {
          fis.close();
        }
        catch(IOException e) {
          e.printStackTrace();
        }
    }
  }

}

but when it run it only prints 64 characters to the standard output (even if the debug string prints 96 bytes in the array, as it should be..) I don't know what I am doing wrong.

Upvotes: 0

Views: 131

Answers (1)

Zoran Regvart
Zoran Regvart

Reputation: 4690

You're need to flush() the System.out, as it will only flush on \n if autoFlush is set (default). See the documentation PrintStream and the option .

Upvotes: 2

Related Questions