为什么附加到BufferedReader会干扰InputStream?

时间:2016-12-07 05:34:48

标签: java inputstream

以下代码有效:

    //Read from an input stream
    FileInputStream inputStream = new FileInputStream("13.png");
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder sb = new StringBuilder();

    String line;
    /*
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    */


    InputStream is = new BufferedInputStream(inputStream);
    Image image = ImageIO.read(is);

    JFrame frame = new JFrame();
    JLabel label = new JLabel(new ImageIcon(image));
    frame.getContentPane().add(label, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);

然而,如果我们取消注释包含附加到BufferedReader的while循环,则会出现错误。

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Main.main(Main.java:63)

为什么会这样?

1 个答案:

答案 0 :(得分:1)

inputStream只能读一次。

FileInputStream inputStream2 = new FileInputStream("13.png");
InputStream is = new BufferedInputStream(inputStream2);
Image image = ImageIO.read(is);

您需要做的是打开一个新的inputStream

{{1}}