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

}

ありがとう!

4

4 に答える 4

1

Unix のみの場合は、locateコマンドを使用できます。updatedbただし、定期的に (できれば自動的に)実行することを忘れないでください。

実際に Java でコマンドライン コマンドを実行するには、この記事を参照してください。基本的なコマンドは ですが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);
        }
    }
}

それ以外の場合は、ファイル ツリーをウォークすることができます(NIO.2 を使用する Java ネイティブ)。ただし、キャッシュされていないため、これにはおそらくもっと時間がかかります。

于 2012-05-07T17:32:43.187 に答える
0

locate コマンドの代わりに (たとえば、必要なデータベースが維持されていない場合)、' find' コマンドを使用できます。

find / -type d -name Foo

この呼び出しは、ファイルシステムの「/」の下にある Foo という名前のディレクトリを見つけます。これは非常に遅くなる可能性があることに注意してください - もし 'locate' が利用可能であれば、おそらくはるかに優れたパフォーマンスを発揮します。

于 2012-05-07T19:03:59.000 に答える
0

このlocateコマンドは、利用可能な場合 (一部のシステムではインデックスの構築が有効になっていない場合があります)、システム上のすべてのユーザーが読み取り可能なディレクトリ内のファイルのパスに対して部分文字列の照合を実行します。

于 2012-05-07T17:32:46.687 に答える
0

正確なlocateコマンドは、

locate -r ~/".*"MyDir

また、必要に応じてデータベースを更新します。

sudo updatedb
于 2013-11-21T08:31:01.197 に答える