如何清除/重置/打开输入流,以便它可以在Java中的两种不同方法中使用?

这是代码:

package testpack; 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+"."); // tried writing System.in.close(); and System.in.reset(); } 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 } } 

这是我运行时的输出(当我调用第一个方法时输入“Something”,第二个方法然后由于某种原因自动读取“omething”而不是让我再次输入..):

 run: 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: You entered the following line of text: omething BUILD SUCCESSFUL (total time: 9 seconds) 

打印出“omething”的原因是,在调用readByte时,只消耗输入的第一个字节。 然后readLine消耗流中的剩余字节。

在readByte方法的末尾尝试这一行: System.in.skip(System.in.available());

这将跳过流中的剩余字节(“omething”),同时仍然打开流以使用readLine的下一个输入。

关闭System.in或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 } } 

结果是:

 $ 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 

更新:正如我们在聊天中讨论的那样,它可以在命令行中运行,但不能在netbeans中运行。 必须是IDE的东西。