簡體   English   中英

Java Runtime.getRuntime()。exec用於帶有非路徑的Unix查找命令

[英]Java Runtime.getRuntime().exec for unix find command with not path

嘗試了多種方法。 當命令在Linux上運行時,刪除一個目錄(除了一個特定的子目錄)下的文件的命令可以正常工作。

通過Java exec運行時,相同的命令似乎無法識別路徑,並且一切都消失了。

find /test/filesdir/filexp -maxdepth 2 ! -path "/test/filesdir/filexp/node1/*" -type f -daystart -mtime +1 -delete

在(“)雙引號之前嘗試過escpace字符\\似乎沒有幫助。

任何想法,請幫助。

使用的Java代碼:

Process RunCmdLine = Runtime.getRuntime().exec(CommandLine);
RunCmdLine.waitFor();
InputStream stdInput = RunCmdLine.getInputStream();
InputStream stdError = RunCmdLine.getErrorStream();
byte buffer[] = new byte [2048];
for (int read; (read = stdInput.read(buffer)) != -1;) {
System.out.write(buffer, 0, read);
inBuff.append(new String(buffer, 0, read));
}
SystemErrMsg[0] = SystemErrMsg[0] + inBuff.toString();

我從數據庫查詢中獲取了命令行字符串,其中有完整的find命令

我在之前添加了sysout(commandline)

Process RunCmdLine = Runtime.getRuntime().exec(CommandLine);

我在服務器上的stdout文件中看到該命令。 看起來不錯,當我在服務器上運行該命令時,它工作正常。

Runtime.exec(String)聲稱另一個受害者!

切勿使用此功能。 它有零個有效用例。 請改用Runtime.exec(String[])版本,或使用(甚至更好) ProcessBuilder

兩者都有兩個常用的成語。 第一個通過在shell中運行命令來模擬C的簡單和草率的system

// I don't care about security, my homework is due and I just want it to work ;_;
String CommandLine = "find /test/filesdir/filexp -maxdepth 2 " 
    + "! -path \"/test/filesdir/filexp/node1/*\" " 
    + "-type f -daystart -mtime +1 -delete";
Runtime.getRuntime().exec(new String[] { "bash", "-c", CommandLine });

和一個更接近C的execv(char*, char**)的安全而強大的版本:

// I have a strong understanding of UNIX and want a robust solution!
String[] commandArgs = new String[] {
    "find", "/test/filesdir/fileexp", "-maxdepth", "2",
      "!", "-path", "/test/filesdir/filexp/node1/*", "-type", "f",
      "-daystart", "-mtime", "+1", "-delete"
};
Runtime.getRuntime().exec(commandArgs);

第一個只要求您知道如何使用外殼。 第二個要求您另外了解shell在后台的工作方式,並且不能根據此示例盲目復制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM