通过使用文件重定向为其提供输入来运行 Java 程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19697922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:29:18  来源:igfitidea点击:

Run Java program by giving it input using file redirection

javacommand-line

提问by Kevin

I'm trying to run a Java program using file redirection. I'm testing it with this simple program:

我正在尝试使用文件重定向运行 Java 程序。我正在用这个简单的程序测试它:

package netbeans.sanbdox;

public class Sanbdox {
    public static void main(String[] args) {
        for(int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

When I go to the command line and run

当我进入命令行并运行时

$ java -jar dist/compiled_project.jar < q1.txt
$ 

There's no output, even though q1.txtis not an empty file. What should I do to make the file redirection work?

即使q1.txt不是空文件,也没有输出。我应该怎么做才能使文件重定向工作?

采纳答案by Chris Hayes

Redirecting in that form just replaces stdinwith a file stream coming from that file. Your code does not use stdinfor anything, therefore you won't have any output, since you aren't passing any command line arguments to the program.

以这种形式重定向只是替换stdin为来自该文件的文件流。您的代码不stdin用于任何事情,因此您不会有任何输出,因为您没有将任何命令行参数传递给程序。

To see what you're expecting, you'd have to use a Scanner:

要查看您的期望,您必须使用Scanner

Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

scanner.close(); // Not required for stdin but good practice

If what you really wanted was to have each token from the file supplied as a command line argument, you could do something like this in your shell:

如果您真正想要的是将文件中的每个标记作为命令行参数提供,您可以在 shell 中执行以下操作:

$ java -jar dist/compiled_project.jar $(cat q1.txt)

That would output the contents of q1.txtas part of the shell command. Odds are it won't work the way you want due to newline characters or other concerns.

这将输出 的内容q1.txt作为 shell 命令的一部分。由于换行符或其他问题,它可能无法按您想要的方式工作。

回答by The Coordinator

The input is captured by the System.inand not as data passed through the main(String[] args) method when the program starts.

System.in当程序启动时,输入由和捕获,而不是作为通过 main(String[] args) 方法传递的数据。

To read that data from the input, read it from System.inas an InputStreamor wrap it in a Reader:

要从输入中读取该数据,请将其System.in作为 an读取InputStream或将其包装在 a 中Reader

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

... s.readLine() 

And make sure to not close the System.in or the Reader, or else you will close keyboard input to your program too!

并确保不要关闭 System.in 或 Reader,否则您也会关闭程序的键盘输入!