Reputation: 537
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
Upvotes: 3
Views: 17896
Reputation: 389
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]});
}
}
Upvotes: 0
Reputation: 15254
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
Upvotes: 11
Reputation: 262850
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.
Upvotes: 9