Tôi đang làm việc trên một ứng dụng có vấn đề về việc chạy lệnh shell từ ứng dụng java. đây là đoạn code:chạy lệnh shell từ java
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();
}
nhưng khi tôi cố gắng để exec lệnh như:
/export/home/test/myapp -T "some argument"
myapp đọc "some argument"
như hai tách arguments.but Tôi muốn đọc "some argument"
như chỉ có một cuộc tranh cãi. khi tôi trực tiếp chạy lệnh này từ thiết bị đầu cuối, nó thực thi thành công. Tôi đã thử '"some argument"'
, ""some argument""
, "some\ argument"
nhưng không hoạt động đối với tôi. làm thế nào tôi có thể đọc đối số này như một đối số.
thx @midhat. điều này làm việc cho tôi. – Aykut
[Khi 'Runtime.exec()' sẽ không: Tự điều hướng xung quanh các cạm bẫy liên quan đến phương thức 'Runtime.exec()' (http://www.javaworld.com/article/2071275/core-java/when -runtime-exec --- won-t.html) hoặc có thể là [truy vấn công cụ tìm kiếm] trong tương lai (https://duckduckgo.com/?q=When+Runtime.exec+wont+Navigate+yourself+around+ cạm bẫy + liên quan + đến + phương thức + Runtime.exec +). –