[英]How to create a java program that runs another java program which will recieve input from a text file?
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:
流程如下:
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.input.txt
然后程序生成一些输出,这些输出将针对预期的输出进行测试(s) 确定一切是否正确。 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:例如
input.txt
包含:
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).
我现在需要做的是检查 output 与正确的 output (该步骤不是问题)。 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: [1] 中的解决方案是首选,但是任一解决方案都无法正确地 function,即问题在这里:
// 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.问题是
input.txt
在这里完全被忽略了,现在 class B 中的扫描仪正在无限期地等待接收输入。 Is there a way to properly handle this ie to feed input.txt
to class B through Java code?有没有办法正确处理这个问题,即通过 Java 代码将
input.txt
提供给 class B?
I have found a way to do it, albeit it's a workaround/hack:我找到了一种方法来做到这一点,尽管它是一种解决方法/黑客:
// 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("/bin/sh check.sh");
}
}
echo `java B < input.txt`
Doing things this way works.以这种方式做事是有效的。
Maybe a little late.也许有点晚了。 but try ProcessBuilder
但尝试 ProcessBuilder
ProcessBuilder builder = new ProcessBuilder("java", "B");
builder.redirectInput(new File("input.txt"));
try {
processRun = builder.start();
} catch (IOException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.