6
public class ReadInput {
    public static void main(String[] args) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String x = null;  
        while( (x = input.readLine()) != null ) {    
            System.out.println(x); 
        }    
    }
}  

我可以通过键入“java ReadInput < input.txt”从命令行运行此代码,但不能像“java ReadInput hello”那样直接键入输入。当我输入“java ReadInput hello”时,由于某种原因,我似乎陷入了无限循环。它不应该以与键入'java ReadInput < input.txt'相同的方式工作,而只是重新打印'hello'?

4

4 回答 4

7

程序命令行中给出的参数不会转到System.in,而是放在args数组中。您可以使用类似的东西echo hello | java ReadInput来运行程序,或者您可以修改程序以查看其args数组并将其视为输入。(如果您使用后一个选项,您可能希望回到阅读 fromSystem.in如果没有任何内容args。)

于 2011-05-07T01:29:45.233 回答
5

Both of the other two answers above are partially correct, but partially misleading.

Using the following syntax...

java ReadInput < input.txt

...the actual command that is run on the java binary is:

java ReadInput

The operating system shell interprets the < sign, and sends the contents of input.txt to the Standard Input Stream (System.in).

When you call System.in.readLine(), the code checks whether there is a line of input available from the Standard Input Stream. When you piped in a file, this means it takes the next line of the file (as if the OS were taking the contents of the file and typing them in at the prompt). When you run the program without piping a file, it will wait until you, the user, provide it with a line of input from the shell and press the return key.

Command-line arguments to the JVM work differently, and do not use the Standard Input Stream (System.in). Ex:

java ReadInput "Input number one" "Input number two"

In this case, you are passing in two command-line arguments. These properties will be available through the args array:

   public static void main(String[] args) throws IOException {
          System.out.println(args.length); //3
          System.out.println(args[0]); //"ReadInput"
          System.out.println(args[1]); //"Input number one"
          System.out.println(args[2]); //"Input number two"
   }

With the code that you provided, the program will end when the result of a readLine() call returns null. I believe you may be able to just push enter at the prompt to send a blank line, and end the program. If not, you may have to fix the program to check for an empty string (input.readLine().equals("")).

Hope this helps.

于 2011-05-10T01:40:59.317 回答
3

当您键入时,java ReadInput hello您还没有(还)提供任何输入,System.in因此程序执行会阻塞,直到有东西要读取。您可能会注意到字符串"hello"被传递到方法的args参数中main()

如果您使用的是调试器(我强烈推荐),请在main(). 您会注意到,当您按原样运行程序时java ReadInput hello,.args[0]"hello"

如果您不使用调试器,则可以使用System.out.println()(这是初学者经常调试代码的方式)。添加这行代码作为第一行main()

if (args.length > 0) System.out.println(args[0]);
于 2011-05-07T01:26:47.087 回答
1

终止标准输入

Ctrl-D  :  Linux/Unix 
Ctrl-Z (or F6) and "Enter" : Windows.

或者设置一个special EOF symbol自己。

于 2015-01-22T07:02:26.227 回答