linux version: MINT 14 netbeans 7.2
I am pretty recent into programming, and I face this difficulty. I have a GUI with 2 jtextarea, one where we type commands, one where the commands output goes (a third one will be implemented for errors (linux, not java) this works ok, for now for my prototype, up to this point:
the output of the command goes into the text area, but it is missing the prompts, I tried many things, but cannot get around to it, I also browsed many faqs, but prompt is used in so many ways, but not in the shell prompt. Help welcome.
I have inserted the code for the process builder class (please ignore for now the best practises like capital letters and so on, it is a prototype only, I will have coders afters if the prototype works)
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 "";
}
}
}