如何将stdin和stdout重定向到java中的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23886499/
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
how to redirect stdin and stdout to a text file in java
提问by slaveCoder
How to redirect stdin and stdout to take data as input from a text file and pass data as output to another textfile.
如何重定向 stdin 和 stdout 以将数据作为文本文件的输入并将数据作为输出传递到另一个文本文件。
My input and output files look like this.
我的输入和输出文件如下所示。
Input File.txt
输入文件.txt
1 2 3
The output should be the sum of the numbers in the input file.
输出应该是输入文件中数字的总和。
Output File.txt
输出文件.txt
6
采纳答案by Thilo
You don't have to do that in Java, you can do it from the shell that runs your Java application:
您不必在 Java 中执行此操作,您可以从运行 Java 应用程序的 shell 中执行此操作:
# cat input.txt | java -jar myapp.jar > output.txt
The Java code can then just read from System.in and write to System.out.
然后,Java 代码可以从 System.in 读取并写入 System.out。
回答by sidgate
You can set the System.out
and System.in
to a file path. Then your existing code should work
您可以将System.out
和System.in
设置为文件路径。那么你现有的代码应该可以工作
System.setIn(new FileInputStream(new File("input.txt")));
...
//read from file
....
System.setOut(new PrintStream(new File("filename.txt")));
System.out.println(sum); // will be printed to the file
回答by zhy2002
This is a reflection based solution incorporating part of code from @sidgate's answer:
这是一个基于反射的解决方案,结合了@sidgate 答案中的部分代码:
import java.lang.reflect.Method;
public class Driver {
public static void main(String[] args) throws Exception {
runSolution("utopiantree");
}
private static void runSolution(String packageName) throws Exception{
System.setIn(Driver.class.getClassLoader().getResourceAsStream(packageName + ".tc"));
Method mainMethod = Class.forName(packageName + ".Solution").getMethod("main", new Class[]{String[].class});
mainMethod.setAccessible(true);
mainMethod.invoke(null, new Object[]{new String[0]});
}
}