70

Javaクラスを介してcmdコマンドを実行するためのコードスニペットをいくつか見つけましたが、理解できませんでした。

これは、cmdを開くためのコードです

public void excCommand(String new_dir){
    Runtime rt = Runtime.getRuntime();
    try {
        rt.exec(new String[]{"cmd.exe","/c","start"});

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

そして、cdhttp ://www.coderanch.com/t/109753/Linux-UNIX/exec-command-cd-command-javaなどの他のコマンドを追加するための他のリンクをいくつか見つけました 。

コマンドプロンプトを開き、Javaを使用してコマンドを挿入するにはどうすればよいですか?

誰かが私が次のようなディレクトリをcdする方法を理解するのを手伝ってくれますか?

 cd C:\Program Files\Flowella

次に、そのディレクトリで他のコマンドを実行しますか?

4

14 に答える 14

149

別のディレクトリからJavaプログラムの作業ディレクトリにプロセスを実行する1つの方法は、ディレクトリを変更してから、同じコマンドラインでプロセスを実行することです。これを行うcmd.exeには、などのコマンドラインを実行し cd some_directory && some_programます。

次の例は別のディレクトリに変更され、dirそこから実行されます。確かに、私はdirそのディレクトリを必要とせずにそのディレクトリを作成することができcdましたが、これは単なる例です。

import java.io.*;

public class CmdTest {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }
    }
}

ProcessBuilderコマンドを実行するためにを使用していることにも注意してください。特に、これにより、を呼び出すことにより、プロセスの標準エラーを標準出力にリダイレクトできますredirectErrorStream(true)。そうすることで、読み取るストリームが1つだけになります。

これにより、私のマシンで次の出力が得られます。

C:\Users\Luke\StackOverflow>java CmdTest
 Volume in drive C is Windows7
 Volume Serial Number is D8F0-C934

 Directory of C:\Program Files\Microsoft SQL Server

29/07/2011  11:03    <DIR>          .
29/07/2011  11:03    <DIR>          ..
21/01/2011  20:37    <DIR>          100
21/01/2011  20:35    <DIR>          80
21/01/2011  20:35    <DIR>          90
21/01/2011  20:39    <DIR>          MSSQL10_50.SQLEXPRESS
               0 File(s)              0 bytes
               6 Dir(s)  209,496,424,448 bytes free
于 2013-03-17T18:23:25.843 に答える
14

あなたはこれを試すことができます:-

Process p = Runtime.getRuntime().exec(command);
于 2013-03-17T17:53:39.057 に答える
8

のようなアクションを実行する場合はcd、次を使用します。

String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));

例:

String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();

コマンドとすべての引数を文字列配列の別々の文字列に分割することが重要です(そうしないと、ProcessBuilderAPIによって正しく提供されません)。

于 2014-12-13T22:59:02.430 に答える
6

これは、コマンドライン実行のより完全な実装です。

使用法

executeCommand("ls");

出力:

12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src

コード

private void executeCommand(String command) {
    try {
        log(command);
        Process process = Runtime.getRuntime().exec(command);
        logOutput(process.getInputStream(), "");
        logOutput(process.getErrorStream(), "Error: ");
        process.waitFor();
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

private void logOutput(InputStream inputStream, String prefix) {
    new Thread(() -> {
        Scanner scanner = new Scanner(inputStream, "UTF-8");
        while (scanner.hasNextLine()) {
            synchronized (this) {
                log(prefix + scanner.nextLine());
            }
        }
        scanner.close();
    }).start();
}

private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");

private synchronized void log(String message) {
    System.out.println(format.format(new Date()) + ": " + message);
}
于 2017-12-27T16:19:09.390 に答える
4

私の例(実際のプロジェクトから)

フォルダ—ファイル。

zipFile、filesString —文字列;

        final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
        logger.info("Start unzipping: {}    into the folder {}", command, folder.getPath());
        final Runtime r = Runtime.getRuntime();
        final Process p = r.exec(command, null, folder);
        final int returnCode = p.waitFor();

        if (logger.isWarnEnabled()) {
            final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = is.readLine()) != null) {
                logger.warn(line);
            }
            final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((line = is2.readLine()) != null) {
                logger.warn(line);
            }
        }
于 2013-03-17T18:08:32.090 に答える
4

これを試して:

Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
于 2016-07-03T22:32:08.997 に答える
3

最も簡単な方法は、を使用することRuntime.getRuntime.exec()です。

たとえば、Windowsのデフォルトブラウザのレジストリ値を取得するには、次のようにします。

String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
    Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
    e.printStackTrace();
}

次にScanner、必要に応じて、を使用してコマンドの出力を取得します。

Scanner kb = new Scanner(process.getInputStream());

\は、のエスケープ文字でありString、正しく機能するにはエスケープする必要があります(したがって、\\)。


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

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

コマンドの最も簡単な方法:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");
于 2013-03-17T17:53:03.957 に答える
2

Processへの参照を取得したら、その上でgetOutpuStreamを呼び出して、cmdプロンプトの標準入力を取得できます。次に、他のストリームと同様に、writeメソッドを使用してストリームを介して任意のコマンドを送信できます。

生成されたプロセスのstdinに接続されているのはprocess.getOutputStream()であることに注意してください。同様に、コマンドの出力を取得するには、getInputStreamを呼び出してから、これを他の入力ストリームとして読み取る必要があります。

于 2013-03-17T18:02:36.907 に答える
2

public class Demo {public static void main(String args [])throws IOException {

    Process process = Runtime.getRuntime().exec("/Users/******/Library/Android/sdk/platform-tools/adb" + " shell dumpsys battery ");
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    while (true) {
        line = in.readLine();
        if (line == null) { break; }
        System.out.println(line);
    }
}

}
于 2020-01-11T16:50:14.420 に答える
2

サービスの停止と無効化は、以下のコードで実行できます。

static void sdService() {
    String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
    try {           
        Process process = new ProcessBuilder(cmd).start();
        process.waitFor();      
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                            
        line = null;
        bufferedReader = null;
        Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
        p.waitFor();
        bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }                   
    } catch (Exception e) {
        e.printStackTrace();
    }                   
}

サービスの有効化と開始は、以下のコードを介して行うことができます

static void esService() {
    String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
                    
    try {
        Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
        //Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
        p.waitFor();        
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                            
        line = null;
        bufferedReader = null;
        Process process = new ProcessBuilder(cmd).start();          
        process.waitFor();
        bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                        
    } catch (Exception e) {
        e.printStackTrace();
    }               
}

任意のフォルダからコマンドを実行するには、以下のコードを使用します。

static void runFromSpecificFolder() {       
    try {
        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
        //processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
        processBuilder.redirectErrorStream(true);
        Process p = processBuilder.start();
        p.waitFor();        
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }                
    } catch (Exception e) {
        e.printStackTrace();
    }               
}
    
public static void main(String args[]) {
    sdService();
    runFromSpecificFolder();
    esService();
}
于 2020-12-29T14:43:05.020 に答える
1

これは実際のプログラムではないcdため、この方法で実行することはできません。cdこれはコマンドラインの組み込み部分であり、コマンドラインの環境を変更するだけです。サブプロセスで実行することは意味がありません。その場合、そのサブプロセスの環境を変更しているためです。ただし、そのサブプロセスはすぐに閉じて、その環境を破棄します。

実際のJavaプログラムで現在の作業ディレクトリを設定するには、次のように記述します。

System.setProperty("user.dir", "C:\\Program Files\\Flowella");
于 2013-03-17T18:12:35.763 に答える
1

Javaからcmdを実行する方法の1つ!

public void executeCmd() {
    String anyCommand="your command";
    try {
        Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);

    } catch (IOException e) {
        e.printStackTrace();
    }
}
于 2019-03-18T02:42:32.613 に答える
0

最も簡単で最短の方法は、CmdToolライブラリを使用することです。

new Cmd()
         .configuring(new WorkDir("C:/Program Files/Flowella"))
         .command("cmd.exe", "/c", "start")
         .execute();

ここで他の例を見つけることができます。

于 2018-04-24T10:49:35.280 に答える
0

ここでの付加価値は、アンパサンドを使用してコマンドをバッチ処理し、CDを使用してドライブを変更するためのフォーマットを修正することです。

public class CmdCommander {

public static void main(String[] args) throws Exception {
    //easyway to start native windows command prompt from Intellij

    /*
    Rules are:
    1.baseStart must be dual start
    2.first command must not have &.
    3.subsequent commands must be prepended with &
    4.drive change needs extra &
    5.use quotes at start and end of command batch
    */
    String startQuote = "\"";
    String endQuote = "\"";
    //String baseStart_not_taking_commands = " cmd  /K start ";
    String baseStart = " cmd  /K start cmd /K ";//dual start is must

    String first_command_chcp = " chcp 1251 ";
    String dirList = " &dir ";//& in front of commands after first command means enter
    //change drive....to yours
    String changeDir = " &cd &I: ";//extra & makes changing drive happen

    String javaLaunch = " &java ";//just another command
    String javaClass = " Encodes ";//parameter for java needs no &

    String javaCommand = javaLaunch + javaClass;
    //build batch command
    String totalCommand =
            baseStart +
                    startQuote +
                    first_command_chcp +
                    //javaCommand +
                    changeDir +
                    dirList +
                    endQuote;

    System.out.println(totalCommand);//prints into Intellij terminal
    runCmd(totalCommand);
    //Thread t = Thread.currentThread();
    //t.sleep(3000);
    System.out.println("loppu hep");//prints into Intellij terminal

}


public static void runCmd(String command) throws Exception {

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command);


}

}

于 2020-01-04T21:21:41.580 に答える