how to redirect stdin and stdout to a text file in

2020-08-09 04:42发布

How to redirect stdin and stdout to take data as input from a text file and pass data as output to another textfile.

My input and output files look like this.

Input File.txt

1 2 3

The output should be the sum of the numbers in the input file.

Output File.txt

6

标签: java
3条回答
Melony?
2楼-- · 2020-08-09 05:03

You don't have to do that in Java, you can do it from the shell that runs your Java application:

# cat input.txt | java -jar myapp.jar > output.txt

The Java code can then just read from System.in and write to System.out.

查看更多
我只想做你的唯一
3楼-- · 2020-08-09 05:05

This is a reflection based solution incorporating part of code from @sidgate's answer:

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]});
    }
}
查看更多
The star\"
4楼-- · 2020-08-09 05:07

You can set the System.out and System.in to a file path. Then your existing code should work

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    
查看更多
登录 后发表回答