Runtime.exec
Hi,
i am trying to simulate a shell using Runtime.exec()
First problem: I cannot browse my filesystem, because the Runtime.exec Command creates a new process every time it is called. How can I solve this problem best? Does my program have to remain the current dir every time the command "cd" was used? Or can i get the dir from the process itself?
Second problem: My Program gets the standard input and the error input stream. But with some commands (like ftp or telnet) i get no input at all.
Maybe it is better if I will attach some of the code, for is it difficult to explain
...
/**
* f齢t einen Befehl in der Konsole aus.
* @param command ein Kommando
* @param wait, true, wenn auf den Output des Kommandos
* gewartet werden soll
*/
public String exec(String command,boolean wait){
try{
buff =new StringBuffer();
// log
if (ui !=null)
ui.addMessage("trying to execute command: " + command);
// OS ermitteln
String osName = System.getProperty("os.name");
String[] cmd =new String[3];
if (osName.equals("Windows NT") || osName.equals("Windows XP")){
cmd[0] ="cmd.exe";
cmd[1] ="/C";
cmd[2] = command;
}elseif (osName.equals("Windows 95")){
cmd[0] ="command.com";
cmd[1] ="/C";
cmd[2] = command;
}elseif (osName.equals("Linux")){
cmd[0] ="/bin/sh";
cmd[1] ="-c";
cmd[2] = command;
}else{
cmd[0] ="";
cmd[1] ="";
cmd[2] = command;
System.out.println("OS nicht spezifiziert: " + osName);
}
Runtime rt = Runtime.getRuntime();
proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler =
new StreamGobbler(proc.getErrorStream(),"ERROR");
// any output?
StreamGobbler outputGobbler =
new StreamGobbler(proc.getInputStream(),"OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// eine Zeitlang auf den Output warten
if (wait){
outputGobbler.join(2000);
errorGobbler.join(2000);
}
System.out.println(buff.toString());
// ui.addMessage(buff.toString());
String s = buff.toString();
//this.workDir =
return s;
}catch (Throwable t){
t.printStackTrace();
returnnull;
}
}
/**
* Absorbiert die Eingabestr齧e (Resultate der Befehle
* in der Konsole)
* @author tobi
*/
class StreamGobblerextends Thread{
InputStream is;
String type;
StreamGobbler(InputStream is, String type){
this.is = is;
this.type = type;
}
publicvoid run(){
try{
InputStreamReader isr =new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
String line =null;
while ((line = br.readLine()) !=null)
buff.append(line +"\n");
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}

