56

Ubuntu10.04ターミナルで「cd」コマンドを使用してディレクトリを変更しようとしているスタンドアロンのJavaアプリケーションを作成しました。次のコードを使用しました。

String[] command = new String[]{"cd",path};
Process child = Runtime.getRuntime().exec(command, null);

しかし、上記のコードは次のエラーを出します

Exception in thread "main" java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory

誰かがそれを実装する方法を教えてもらえますか?

4

8 に答える 8

66

別のプロセスで実装できないcdため、と呼ばれる実行可能ファイルはありません。

問題は、各プロセスに独自の現在の作業ディレクトリがあり、個別のプロセスとして実装すると、そのcdプロセスの現在の作業ディレクトリのみが変更されることです。

Javaプログラムでは、現在の作業ディレクトリを変更することはできず、変更する必要はありません。絶対ファイルパスを使用するだけです。

現在の作業ディレクトリが重要な1つのケースは、外部プロセスの実行です(ProcessBuilderまたはを使用Runtime.exec())。そのような場合、新しく開始されたプロセスに使用する作業ディレクトリを明示的に指定できます(それぞれProcessBuilder.directory()および3つの引数Runtime.exec())。

注:現在の作業ディレクトリは、システムプロパティ から読み取ることができますuser.dir。そのシステムプロパティを設定したくなるかもしれません。これを行うと、書き込み可能であることが意図されていないため、非常に悪い不整合が発生することに注意してください。

于 2011-02-03T10:05:23.383 に答える
21

以下のリンクを参照してください(これはそれを行う方法を説明しています):

http://alvinalexander.com/java/edu/pj/pj010016

すなわち:

String[] cmd = { "/bin/sh", "-c", "cd /var; ls -l" };
Process p = Runtime.getRuntime().exec(cmd);
于 2014-01-14T17:44:54.713 に答える
14

このexecコマンドをJavaランタイムで調べたことがありますか。「cd」するパスを使用してファイルオブジェクトを作成し、それをexecメソッドの3番目のパラメーターとして入力します。

public Process exec(String command,
                String[] envp,
                File dir)
         throws IOException

指定された環境と作業ディレクトリを使用して、指定された文字列コマンドを別のプロセスで実行します。

これは便利な方法です。exec(command、envp、dir)形式の呼び出しは、exec(cmdarray、envp、dir)の呼び出しとまったく同じように動作します。ここで、cmdarrayは、コマンド内のすべてのトークンの配列です。

より正確には、コマンド文字列は、文字カテゴリをさらに変更することなく、new StringTokenizer(command)の呼び出しによって作成されたStringTokenizerを使用してトークンに分割されます。次に、トークナイザーによって生成されたトークンは、同じ順序で新しい文字列配列cmdarrayに配置されます。

Parameters:
    command - a specified system command.
    envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.
    dir - the working directory of the subprocess, or null if the subprocess should inherit the working directory of the current process. 
Returns:
    A new Process object for managing the subprocess 
Throws:
    SecurityException - If a security manager exists and its checkExec method doesn't allow creation of the subprocess 
    IOException - If an I/O error occurs 
    NullPointerException - If command is null, or one of the elements of envp is null 
    IllegalArgumentException - If command is empty
于 2014-07-18T07:24:14.913 に答える
6

このコマンドは問題なく機能します

Runtime.getRuntime().exec(sh -c 'cd /path/to/dir && ProgToExecute)
于 2015-04-04T17:47:50.260 に答える
2

プロセスビルダーのメソッドの1つを使用して、cmdが実行されると予想されるディレクトリを渡すことができます。以下の例をご覧ください。また、wait forメソッドを使用して、プロセスのタイムアウトについて言及することもできます。

ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", cmd).directory(new File(path));

        Process p = builder.start();

        p.waitFor(timeoutSec, TimeUnit.SECONDS);

上記のコードでは、パスのファイルオブジェクト[cmdが実行されると予想される場所]をProcessBuilderのディレクトリメソッドに渡すことができます。

于 2018-11-10T21:59:08.027 に答える
1

使用してみてください:

Runtime.getRuntime.exec("cmd /c cd path"); 

これはうまくいきました

Runtime r = Runtime.getRuntime(); 
r.exec("cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"); 

以下は機能しませんでした が、アレイコマンドを使用しても機能しませんでした

String[] cmd = {"cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"}; r.exec(cmd);

参考までに、ユーティリティを使用して、上記のウィンドウがWindows以外で機能するかどうかをOSで確認しています。cmd/cを削除します。

于 2017-04-05T16:28:13.213 に答える
1

これに対する私の好ましい解決策は、Runtimeプロセスが実行されるディレクトリを渡すことです。次のような小さなメソッドを作成します。-

    public static String cmd(File dir, String command) {
        System.out.println("> " + command);   // better to use e.g. Slf4j
        System.out.println();        
        try {
            Process p = Runtime.getRuntime().exec(command, null, dir);
            String result = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
            String error = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
            if (error != null && !error.isEmpty()) {  // throw exception if error stream
                throw new RuntimeException(error);
            }
            System.out.println(result);   // better to use e.g. Slf4j
            return result;                // return result for optional additional processing
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

これはApacheCommonsIOライブラリを使用することに注意してください。pom.xml

   <dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>2.10.0</version>
   </dependency>

メソッドを使用するには、cmd例えば

public static void main(String[] args) throws Exception {
    File dir = new File("/Users/bob/code/test-repo");
    cmd(dir, "git status");
    cmd(dir, "git pull");
}

これは次のようなものを出力します:-

> git status

On branch main
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

> git pull

Already up to date.
于 2021-06-28T15:32:45.170 に答える
0

これを解決するには、Javaアプリケーションに同じディレクトリにあるshスクリプトを実行させてから、shスクリプトで「cd」を実行しました。

ターゲットアプリケーションが正しく動作するように、特定のディレクトリに対して「cd」を実行する必要がありました。

于 2017-05-03T19:19:02.400 に答える