FileInputStream如何读取工作?

时间:2016-04-22 19:54:39

标签: java fileinputstream

有人请解释我如何在以下代码中填充缓冲区数组:

try {
        byte[] buffer = new byte[1024];
        //(1) this print an empty string?
        System.out.println("1: " + new String(buffer));
        FileInputStream inputStream = new FileInputStream("test.txt");
        int len;

        while((len = inputStream.read(buffer)) != -1) {
            //(2) this print text on my file?
            System.out.println("2: " + new String(buffer));
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

更新:阅读以下内容后,我获得了有用的信息: https://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

  

缓冲输入流从称为缓冲区的存储区读取数据;仅当缓冲区为空时才调用本机输入API。类似地,缓冲输出流将数据写入缓冲区,仅当缓冲区已满时才调用本机输出API

全部谢谢!

1 个答案:

答案 0 :(得分:2)

InputStream#read方法将输入流中的数据读入提供的缓冲区。

有关详细信息,请参阅java doc

(特别是,请参阅返回值 - 如果没有更多数据需要读取,它将返回-1。)