new String(bytes , 0 , length) StringIndexOutOfBoundsException错误

//结果报错StringIndexOutOfBoundsException,为什么不能直接用bfs.read(bytes),length的作用是什么?

public class Demo04 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        try {
            FileInputStream fis = new FileInputStream("1.txt");
            BufferedInputStream bfs = new BufferedInputStream(fis);
            byte[] bytes = new byte[1024];
//            int length = 0;
//            while ((length = bfs.read(bytes)) > 0) {
//                System.out.println(new String(bytes, 0, length));
//            }

            while ((bfs.read(bytes)) > 0) {
                System.out.println(new String(bytes, 0, bfs.read(bytes)));
            }
            bfs.close();
            fis.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
  • 这里其实 读取了两遍, 如果文件此时读取最后一块数据, while循环里已经读取完了,下面再读取就 返回 -1, 自然 new String 那就报错了

img

  • 上面的读取用一个 整型变量接收一下,下面直接使用这个整形变量初始化String即可
int tmp;
while ((tmp = bfs.read(bytes)) > 0) {
    System.out.println(new String(bytes, 0, tmp));
}

下标越界了,自己检查一下吧