问题描述
我的应用程序是获取c ++ CPP文件并进行编译,然后运行它。一切似乎都很完美。但是当用户忘记了输入但c ++程序需要输入时,程序将停止工作。所以有一种方法可以知道c ++程序是否需要用户输入,以便当用户忘记输入时我可以处理这种情况?如果没有的话,我该如何治疗?
select result from range_results
where lower >= (select numbers from codes)
and upper <= (select numbers from codes)
解决方法
经过大量搜索并了解了此错误之后,我发现无法知道进程是否在写入输出之前先等待输入,而且Process
class中也无法停止例如,当c ++程序需要两个输入并且用户仅输入一个输入时,java程序就不会冻结并停止工作。
如何处理这种情况:如以下新代码所示,我使用了Thread
来使Java程序在这种情况下保持活动状态并阻止其冻结。 >
public byte runFile(String input,byte compilere,String fileName) {
try {
ProcessBuilder processBuilder = new ProcessBuilder();
if (compilere == 0) // c++ code
processBuilder.command("bash","-c","./a.out");
else
processBuilder.command("bash","java " + fileName);
Process process = processBuilder.start();
BufferedOutputStream writer = new BufferedOutputStream(process.getOutputStream());
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
if (!input.isEmpty()) {
writer.write((input + "\n").getBytes());
writer.flush();
} else {
textArea2.setText("Input field is empty!");
return 1;
}
// Read the output from the command:
thread1 = new Thread() {
public void run() {
try {
String s = null;
s = stdInput.readLine();
if (s != null) {
textArea2.setText(s);
while ((s = stdInput.readLine()) != null)
textArea2.setText(textArea2.getText() + "\n" + s);
}
thread2.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Read any errors from the attempted command:
thread2 = new Thread() {
public void run() {
try {
String s = null;
s = stdError.readLine();
if (s != null) {
textArea2.setText(s);
while ((s = stdError.readLine()) != null)
textArea2.setText(textArea2.getText() + "\n" + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread1.start();
thread3 = new Thread() {
@Override
public void run() {
try {
sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (textArea2.getText().isEmpty()) {
textArea2.setText("The input is not complete or the your program is slow !");
}
}
};
thread3.start();
} catch (Exception e) {
textArea2.setText(textArea2.getText() + "\n" + e.toString());
e.printStackTrace();
return 1;
}
return 0;
}
编辑:在洛恩侯爵发表评论之后,我处理了没有输入且c ++应用需要输入的情况。