通过使用文件重定向提供输入来运行Java程序 [英] Run Java program by giving it input using file redirection

查看:255
本文介绍了通过使用文件重定向提供输入来运行Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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]);
        }
    }
}

当我转到命令时line and run

When I go to the command line and run

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

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

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

推荐答案

在该表单中重定向只是替换 stdin 包含来自该文件的文件流。您的代码不使用 stdin ,因此您不会有任何输出,因为您没有将任何命令行参数传递给程序。

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

要查看您的期望,您必须使用扫描仪

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

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

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

如果您真正想要的是拥有来自作为命令行参数提供的文件,您可以在shell中执行以下操作:

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:

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

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

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

这篇关于通过使用文件重定向提供输入来运行Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆