文件输入流异常行为



我有以下简单的代码,从当前目录中的文件读取到字节数组,并打印数组的内容(即文件的内容,从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文档和选项。

最新更新