文件输入流奇怪的行为

file input stream odd behaviour

我有以下简单代码,从当前目录中的文件读取到字节数组并打印数组的内容(这是文件的内容,从 ASCII 32 到 ASCII 126 的 ASCII 可打印字符):

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();
        }
    }
  }

}

但是当它 运行 时它只打印 64 个字符到标准输出(即使调试字符串在数组中打印 96 个字节,因为它应该是..) 我不知道我做错了什么。

您需要 flush() System.out,因为如果设置了 autoFlush(默认),它只会在 \n 上刷新。请参阅文档 PrintStream 和选项 .