我正在尝试编译和执行作为Java文件参数的C,C ++和Java代码,然后检查生成的解决方案是否正确,因为大多数网站都会判断解决方案。有人可以告诉我为什么我的代码进入无限循环, file_name_output.txt 中没有输出。我的其他所有文件都是正确的,因为我通过在终端上运行程序来测试它们。这是我的代码:
import java.io.*;
import java.util.Scanner;
class test
{
public static void main(String args[])
{
String s=null,file_name,extension;
int pos = args[0].lastIndexOf(".");
extension = args[0].substring(pos+1);
file_name = args[0].substring(0,pos);
int lang = 0; // 1 -> c,c++ , 2 -> java
try
{
Process compile = null;
switch(extension)
{
case "c" : compile = Runtime.getRuntime().exec("gcc -g "+ args[0] + " -o "+file_name+" -lm");
lang = 1;
break;
case "cpp" : compile = Runtime.getRuntime().exec("g++ -g "+ args[0] + " -o "+file_name);
lang = 1;
break;
case "java" : compile = Runtime.getRuntime().exec("javac "+ args[0]);
lang = 2;
}
BufferedReader stdError = new BufferedReader(new InputStreamReader(compile.getErrorStream()));
if((s = stdError.readLine()) != null)
{
System.out.println("Compile Time Error OR Warning : ");
System.out.println(s);
while((s = stdError.readLine()) != null)
{
System.out.println(s);
}
}
double startTime, run_time;
Process run;
if(lang == 1)
{
startTime = System.nanoTime();
run = Runtime.getRuntime().exec("./"+file_name+" < "+file_name+"_input.txt > "+file_name+"_output.txt");
run_time = (System.nanoTime()-startTime)/(double)Math.pow(10,6);
}
else
{
startTime = System.nanoTime();
run = Runtime.getRuntime().exec("java "+file_name+" < "+file_name+"_input.txt > "+file_name+"_output.txt");
run_time = (System.nanoTime()-startTime)/(double)Math.pow(10,6);
}
System.out.println("RunTime : "+ run_time+" ms");
BufferedReader out_put = new BufferedReader(new FileReader(new File(file_name+"_output.txt")));
BufferedReader run_stdError = new BufferedReader(new InputStreamReader(run.getErrorStream()));
if(( s = run_stdError.readLine()) != null)
{
System.out.println("Runtime Error : ");
System.out.println(s);
while((s = run_stdError.readLine()) != null )
{
System.out.println(s);
}
}
else if((s = out_put.readLine()) != null)
{
String s_string = null;
int failed = 0;
File fs = new File(file_name+".txt");
BufferedReader br = new BufferedReader(new FileReader(fs));
if((!s.equals(s_string = br.readLine())))
{
failed = 1;
}
while(((s = out_put.readLine()) != null) & ((s_string = br.readLine()) != null) & (failed == 0))
{
if(!s.equals(s_string) )
{
failed = 1;
break;
}
}
if((failed == 1) || s != null || s_string != null)
{
System.out.println("Submmision Failed : ");
System.out.println("Either Output Is Wrong.\nOR\nYour Output Is Not According To The Given Format. ");
System.exit(0);
}
else
{
System.out.println("Submission Successful.");
}
}
}
catch(IOException e)
{
System.out.println("Some Error Has Occured : ");
e.printStackTrace();
System.exit(-1);
}
}
}
答案 0 :(得分:5)
你的程序不是无限循环,它是阻止,这就是它发生的地方:
s = run_stdError.readLine()
除非子进程的stderr
上有什么东西,否则这将阻塞直到进程终止。但是,在此等待时,您不会使用该进程的stdout
。它填充其输出缓冲区和块。
结果:进程间死锁。
使用ProcessBuilder
并使用其API实现重定向到文件,而无需您自己的努力。您有redirectOutput(File)
和redirectError(File)
方法。