簡體   English   中英

find命令不適用於Java,但適用於系統外殼

[英]find command works not on java, but in system shell

在Java程序中,我想在目錄/my/dir找到隱藏文件.file.xyz的路徑。 它包含一個不應搜索的子文件夾excludedFolder
所以我用find搜索這個文件。 我用-prune排除了所需的文件夾。

String findCommand = "find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print";
try{
   Process process = Runtime.getRuntime().exec(findCommand);
   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
   //nothing is shown here, but hsould
   bufferedReader.lines().forEach(System.out::println);
}catch(Exception e){
    System.err.println(e.getMessage());
}

如果我將命令粘貼到終端中並在其中執行。 工作正常。
我的操作系統是Ubuntu 16.04。
你能解釋一下為什么嗎?

您需要調用“ sh”並將管道命令傳遞給該程序。 嘗試:

ProcessBuilder b = new ProcessBuilder( "/bin/sh", "-c",
               "find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print" );

您使用Runtime的錯誤exec()函數。

給定

String findCommand = "find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print";

Java代碼

Runtime.getRuntime().exec(findCommand);

將嘗試運行字面上名為"find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print"作為命令。

您想傳遞參數以find ,而不是運行一些長文件名看起來像命令的長命令。 為此,您需要將String 數組傳遞給exec()

String findCommand[] = { "find", "/my/dir", "-path",
    "/my/dir/excludedFolder", "-prune", "-o", "-name", ".file.xyz", "-print" };
...
Runtime.getRuntime().exec(findCommand);

暫無
暫無

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

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