sách gpt4 ai đã đi

java - 从java运行shell命令

In lại 作者:塔克拉玛干 更新时间:2023-11-03 04:11:07 26 4
mua khóa gpt4 Nike

我正在处理一个应用程序,遇到有关从 Java 应用程序运行 shell 命令的问题。这是代码:

public String execRuntime(String cmd) {

Process proc = null;
int inBuffer, errBuffer;
int result = 0;
StringBuffer outputReport = new StringBuffer();
StringBuffer errorBuffer = new StringBuffer();

thử {
proc = Runtime.getRuntime().exec(cmd);
} bắt (IOException e) {
return "";
}
thử {
response.status = 1;
result = proc.waitFor();
} bắt (InterruptedException e) {
return "";
}
if (proc != null && null != proc.getInputStream()) {
InputStream is = proc.getInputStream();
InputStream es = proc.getErrorStream();
OutputStream os = proc.getOutputStream();

thử {
while ((inBuffer = is.read()) != -1) {
outputReport.append((char) inBuffer);
}

while ((errBuffer = es.read()) != -1) {
errorBuffer.append((char) errBuffer);
}

} bắt (IOException e) {
return "";
}
thử {
is.close();
is = null;
es.close();
es = null;
os.close();
os = null;
} bắt (IOException e) {
return "";
}

proc.destroy();
proc = null;
}


if (errorBuffer.length() > 0) {
người ghi nhật ký
.error("could not finish execution because of error(s).");
logger.error("*** Error : " + errorBuffer.toString());
return "";
}


return outputReport.toString();
}

但是当我尝试执行如下命令时:

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

myapp 将 "some argument" 读取为两个单独的参数。但我只想将 "some argument" 读取为一个参数。 当我直接从终端运行这个命令时,它执行成功。我试过 '"some argument"' ,""some argument"" , "some\argument" 但对我不起作用。我怎样才能将这个论点理解为一个论点。

1 Câu trả lời

我记得 exec 方法的重载为参数单独提供了一个参数。你需要使用它

是的。在这里

public Process exec(String[] cmdarray)
throws IOException

只需将命令行和所有参数分隔成字符串数组的元素

关于java - 从java运行shell命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2460297/

26 4 0
Bài viết được đề xuất: java - DAO、Spring 和 Hibernate
Bài viết được đề xuất: .net - ASP.NET VB - Một số phép toán trong .NET
Bài viết được đề xuất: algorithm - 字符串匹配
Bài viết được đề xuất: java - 无法在应用引擎中保留 jpa 实体
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com