Run shell command from java

I am working on an application, I have a problem with running a shell command from a java application. here is the code:

public String execRuntime(String cmd) { Process proc = null; int inBuffer, errBuffer; int result = 0; StringBuffer outputReport = new StringBuffer(); StringBuffer errorBuffer = new StringBuffer(); try { proc = Runtime.getRuntime().exec(cmd); } catch (IOException e) { return ""; } try { response.status = 1; result = proc.waitFor(); } catch (InterruptedException e) { return ""; } if (proc != null && null != proc.getInputStream()) { InputStream is = proc.getInputStream(); InputStream es = proc.getErrorStream(); OutputStream os = proc.getOutputStream(); try { while ((inBuffer = is.read()) != -1) { outputReport.append((char) inBuffer); } while ((errBuffer = es.read()) != -1) { errorBuffer.append((char) errBuffer); } } catch (IOException e) { return ""; } try { is.close(); is = null; es.close(); es = null; os.close(); os = null; } catch (IOException e) { return ""; } proc.destroy(); proc = null; } if (errorBuffer.length() > 0) { logger .error("could not finish execution because of error(s)."); logger.error("*** Error : " + errorBuffer.toString()); return ""; } return outputReport.toString(); } 

but when I try to execute the exec command, for example:

 /export/home/test/myapp -T "some argument" 

myapp reads "some argument" as two separate arguments. But I want to read "some argument" as the only argument. when I directly run this command from the terminal, it completed successfully. I tried '"some argument"' , ""some argument"" , "some\ argument" but didn't work for me. how can i read this argument as one argument.

+7
java exec
source share
2 answers

I remember that overloading the exec method provides a parameter for the arguments separately. You have to use this

Yeah. Here he is

 public Process exec(String[] cmdarray) throws IOException 

Just enter the command line and all arguments. Individual elements of the String array

+16
source share

first make a line
String cmd = "/ export / home / test / myapp -T \" some argument \ ";

then run cmd in proc

-3
source share

All Articles