我正在处理一个应用程序,有一个关于从java应用程序运行shell命令的问题.这是代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试执行命令时:
/export/home/test/myapp -T "some argument"
Run Code Online (Sandbox Code Playgroud)
myapp读"some argument" 作两个分开的论点.但我想读"some argument"作只是一个论点.当我从终端直接运行此命令时,它执行成功.我试过'"some argument"',""some argument"","some\ argument" 但对我没有工作.我怎么能把这个论点看作一个论点.
Mid*_*hat 16
我记得exec方法的重载分别为参数提供了一个参数.你需要使用它
对.就这个
public Process exec(String[] cmdarray)
throws IOException
Run Code Online (Sandbox Code Playgroud)
只需使命令行和所有参数分离String数组的元素即可
| 归档时间: |
|
| 查看次数: |
17200 次 |
| 最近记录: |