使用命令行使用Java管道输入 [英] Piping Input using Java using command line
问题描述
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'?
I am able to run this code from the command line by typing 'java ReadInput < input.txt' but not by typing the input directly like 'java ReadInput hello'. When I type 'java ReadInput hello' I seem to get stuck in an infinite loop for some reason. Shouldn't it just work in the same way as typing 'java ReadInput < input.txt' but instead just reprint 'hello'?
推荐答案
程序命令行中给出的参数不会转到 System.in
,它们进入 args
数组。您可以使用类似 echo hello |的内容java ReadInput
运行该程序,或者您可以修改程序以查看其 args
数组并将其视为输入。 (如果您使用后一种选项,如果 args $ c中没有任何内容,您可能希望退回到读取
System.in
$ c>。)
Arguments given on the program's command line don't go to System.in
, they go in the args
array. You could use something like echo hello | java ReadInput
to run the program, or you could modify the program to to look at its args
array and treat it as input. (If you use the latter option, you'd probably want to fall back to reading from System.in
if there's nothing in args
.)
这篇关于使用命令行使用Java管道输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!