2012-05-07 111 views
2

有沒有可以找到給定目錄的任何(unix)命令?查找給定目錄的命令

因此,例如,我有一個名爲「MyDir」的目錄,但我不知道它在磁盤上的絕對路徑。是否有任何命令可以讓MyDir路徑通過?

更具體地說,我想在Java程序(通過系統調用)中執行此操作。

// return the full path to the specified directory 
// if there's more than once directory with the given name 
// just return the first one. 
static String findPath (String dirName) 
{ 
    // CODE here 

} 

謝謝!

回答

0

locate命令(如果可用)(某些系統可能沒有構建其索引啓用)將對系統上所有世界可讀目錄中的文件路徑執行子字符串匹配。

1

如果只是Unix,可以使用locate命令。不要忘記定期運行updatedb,儘管(最好是自動)。

要真正在Java中運行命令行命令,請查看this article。基本的命令是Runtime#exec,但你會想做一些錯誤檢查。在文章中提供的片段是:

import java.io.*; 

public class JavaRunCommand { 

    public static void main(String args[]) { 

     String s = null; 

     try { 

     // run the Unix "ps -ef" command 
      // using the Runtime exec method: 
      Process p = Runtime.getRuntime().exec("ps -ef"); 

      BufferedReader stdInput = new BufferedReader(new 
       InputStreamReader(p.getInputStream())); 

      BufferedReader stdError = new BufferedReader(new 
       InputStreamReader(p.getErrorStream())); 

      // read the output from the command 
      System.out.println("Here is the standard output of the command:\n"); 
      while ((s = stdInput.readLine()) != null) { 
       System.out.println(s); 
      } 

      // read any errors from the attempted command 
      System.out.println("Here is the standard error of the command (if any):\n"); 
      while ((s = stdError.readLine()) != null) { 
       System.out.println(s); 
      } 

      System.exit(0); 
     } 
     catch (IOException e) { 
      System.out.println("exception happened - here's what I know: "); 
      e.printStackTrace(); 
      System.exit(-1); 
     } 
    } 
} 

否則,你可以Walk the File Tree(使用NIO.2 Java本機)。但這可能需要更長的時間,因爲它沒有被緩存。

+0

嗯,我可能已經選擇了一個錯誤的話,給了什麼,我想一個錯覺做。當我查看「locate」手冊時,似乎從某些數據庫中找到了一些東西。但我的程序需要運行而不依賴於任何數據庫。試想一下,當你打開一個搜索窗口(在Windows上,或在Mac OS上的Finder)並進行搜索。 –

+2

locate數據庫是您的系統管理員可以維護的數據庫(通過上述updatedb命令)。它是反映它所運行系統的文件系統的數據庫。本質上,它是Windows/Finder搜索將用於加速索引文件系統搜索的同一種數據庫。如果你不想依賴那個索引,你可以使用find命令 - 查看我的答案。 – Sbodd

0

作爲替代定位命令(如果說,是不是維持所需的數據庫),你可以使用「find」命令:

find/-type d -name Foo 

此調用會發現名爲Foo任何目錄在文件系統的'/'下的任何地方。請注意,這可能非常非常緩慢 - 如果「定位」可用,那可能會更好。

0

精確定位命令是,

locate -r ~/".*"MyDir 

,如果刷新分貝需要,

sudo updatedb