I am writing a simple online judge, thus I need a way to test the code a user has written. The flow is as follows:
- User writes a program that tries to solve the task which was given to him. For example a program to calculate the square of a number.
- The program is then given an input file (to be precise there will be many such files for each test case there is one), for example
input.txt
and then the program generates some output(s) which will be tested against the expected output(s) to determine if everything is correct.
So let's say that an user has written the following code to solve a problem to find the square of a number:
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(n * n);
}
}
If I run this program from the terminal, I can do this:
$ javac B.java
$ java B < input.txt
Where for example input.txt
contains:
5
The program will execute correctly. What I need to do now is to check that output against the correct output (that step isn't the problem). However I need to automate this task and for this I've read these answers:
The solution in [1] is preferred, however either solution fails to function properly, namely the issue is here:
// omitted most of the code for brevity, similar code as in [2]
public class A {
public static void main(String[] args) {
// Fails to pass input.txt to Scanner from class B i.e. that file is being ignored
processRun = Runtime.getRuntime().exec("java B < input.txt");
}
}
The issue is that input.txt
is completely ignored here and that now the Scanner in class B is waiting indefinitely to receive an input. Is there a way to properly handle this i.e. to feed input.txt
to class B through Java code?