linux版本:MINT 14 netbeans 7.2
我最近才开始编程,我面临着这个困难。我有一个带有 2 个 jtextarea 的 GUI,一个是我们键入命令的地方,一个是命令输出的地方(第三个将针对错误(linux,而不是 java)实现,这可以正常工作,目前对于我的原型,到目前为止:
命令的输出进入文本区域,但缺少提示,我尝试了很多东西,但无法解决它,我也浏览了很多常见问题解答,但提示用于多种方式,但不是在 shell迅速的。欢迎帮助。
我已经插入了流程构建器类的代码(请暂时忽略大写字母等最佳实践,它只是一个原型,如果原型有效,我将有编码员跟进)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
/**
*
* @author bane
*/
public class myprocessBuilderRunCommand {
public static String myprocessBuilderRunCommand(String command, boolean waitForResponse) {
String response = "";
ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
pb.redirectErrorStream(true);
System.out.println("Linux command: " + command);
try {
Process shell = pb.start();
if (waitForResponse) {
// To capture output from the shell
InputStream shellIn;
shellIn = shell.getInputStream();
// Wait for the shell to finish and get the return code
int shellExitStatus = shell.waitFor();
System.out.println("Exit status" + shellExitStatus);
response = convertStreamToStr(shellIn);
shellIn.close();
}
}
catch ( IOException | InterruptedException e) {
System.out.println("Error occured while executing Linux command. Error Description: "
+ e.getMessage());
}
return response;
}
/*
* To convert the InputStream to String we use the Reader.read(char[]
* buffer) method. We iterate until the Reader return -1 which means
* there's no more data to read. We use the StringWriter class to
* produce the string.
*/
public static String convertStreamToStr(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader;
reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
else {
return "";
}
}
}