How to clear/reset/open an input stream so it can be used in 2 different methods in Java?

↘锁芯ラ 提交于 2019-12-06 09:46:50

The reason it prints out "omething" is that in your call to readByte, you only consume the first byte of your input. Then readLine consumes the remainder of the bytes in the stream.

Try this line at the end of your readByte method: System.in.skip(System.in.available());

That will skip over the remaining bytes in your stream ("omething") while still leaving your stream open to consume your next input for readLine.

Its generally not a good idea to close System.in or System.out.

import java.io.*;

public class InputStreamReadDemo {


    private void readByte() throws IOException {
        System.out.print("Enter the byte of data that you want to be read: ");        
        int a = System.in.read();
        System.out.println("The first byte of data that you inputted corresponds to the binary value "+Integer.toBinaryString(a)+" and to the integer value "+a+".");
        System.in.skip(System.in.available());
    }
    private void readLine() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter a line of text: ");
        String res = br.readLine();
        System.out.println("You entered the following line of text: "+res);
        // ... and tried writing br.close();
        // but that messes things up since the input stream gets closed and reset..
    }

    public static void main(String[] args) throws IOException {
        InputStreamReadDemo isrd = new InputStreamReadDemo();
        isrd.readByte();                                                // method 1
        isrd.readLine();                                                // method 2
    }
}

Results in:

$ java InputStreamReadDemo
Enter the byte of data that you want to be read: Something
The first byte of data that you inputted corresponds to the binary value 1010011 and to the integer value 83.
Enter a line of text: Another thing
You entered the following line of text: Another thing

UPDATE: As we discussed in chat, it works from the command line, but not in netbeans. Must be something with the IDE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!