Javaアプリケーションからバッチファイルを実行するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/615948

  •  03-07-2019
  •  | 
  •  

質問

Javaアプリケーションで、" scons -Q implicit-deps-changed build \ file_load_type export \ file_load_type "

を呼び出すバッチファイルを実行します。

バッチファイルを実行することさえできないようです。私はアイデアがありません。

これは私がJavaで持っているものです:

Runtime.
   getRuntime().
   exec("build.bat", null, new File("."));

以前は、実行したいPython Sconscriptファイルがありましたが、それが機能しなかったため、バッチファイルを介してスクリプトを呼び出すことにしましたが、その方法はまだ成功していません。

役に立ちましたか?

解決

バッチファイルは実行可能ファイルではありません。それらを実行するにはアプリケーション(cmd)が必要です。

UNIXでは、スクリプトファイルのファイルの先頭にシバン(#!)があり、それを実行するプログラムを指定します。 Windowsでのダブルクリックは、Windowsエクスプローラーによって実行されます。 CreateProcess はそれについて何も知りません。

Runtime.
   getRuntime().
   exec("cmd /c start \"\" build.bat");

注: start \" \" コマンドを使用すると、タイトルが空白の別のコマンドウィンドウが開き、バッチファイルからの出力がそこに表示されます。また、「cmd / c build.bat」だけで動作するはずです。この場合、必要に応じてJavaのサブプロセスから出力を読み取ることができます。

他のヒント

スレッド実行プロセス時間は、JVMスレッド待機プロセス時間よりも長い場合があります。これは、呼び出しているプロセスの処理に時間がかかる場合に発生します。次のようにwaitFor()コマンドを使用します。

try{    
    Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
    p.waitFor();

}catch( IOException ex ){
    //Validate the case the file can't be accesed (not enought permissions)

}catch( InterruptedException ex ){
    //Validate the case the process is being stopped by some external situation     

}

この方法により、スレッド実行スタックを続行する前に、呼び出しているプロセスが完了するまでJVMが停止します。

Runtime runtime = Runtime.getRuntime();
try {
    Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
    InputStream is = p1.getInputStream();
    int i = 0;
    while( (i = is.read() ) != -1) {
        System.out.print((char)i);
    }
} catch(IOException ioException) {
    System.out.println(ioException.getMessage() );
}

Javaを使用してバッチファイルを実行する場合は...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

これでうまくいくはずです。

ProcessBuilder はJava 5 /外部プロセスを実行する6つの方法。

バッチスクリプトの実行に使用される実行可能ファイルは cmd.exe で、 / c フラグを使用して実行するバッチファイルの名前を指定します。

Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});

理論的には、この方法でSconsを実行できるはずですが、私はこれをテストしていません:

Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});

編集:アマラ、あなたはこれが機能していないと言います。リストしたエラーは、WindowsボックスでCygwin端末からJavaを実行するときに表示されるエラーです。これはあなたがしていることですか?問題は、WindowsとCygwinのパスが異なるため、WindowsバージョンのJavaがCygwinパスで実行可能なsconsを見つけられないことです。これがあなたの問題であることが判明した場合、さらに説明できます。

Process p = Runtime.getRuntime().exec( 
  new String[]{"cmd", "/C", "orgreg.bat"},
  null, 
  new File("D://TEST//home//libs//"));

jdk1.5およびjdk1.6でテスト済み

これは私にとってはうまくいきました。他の人にも役立つことを願っています。 これを得るために、私はもっと苦労しました。 :(

同じ問題がありました。ただし、CMDがファイルの実行に失敗することがありました。 だからこそ、デスクトップにtemp.batを作成し、次にこのtemp.batでファイルを実行し、次にtempファイルを削除します。

これはより大きなコードであることはわかっていますが、Runtime.getRuntime()。exec()でさえ失敗したときでも100%で機能しました。

// creating a string for the Userprofile (either C:\Admin or whatever)
String userprofile = System.getenv("USERPROFILE");

BufferedWriter writer = null;
        try {
            //create a temporary file
            File logFile = new File(userprofile+"\\Desktop\\temp.bat");   
            writer = new BufferedWriter(new FileWriter(logFile));

            // Here comes the lines for the batch file!
            // First line is @echo off
            // Next line is the directory of our file
            // Then we open our file in that directory and exit the cmd
            // To seperate each line, please use \r\n
            writer.write("cd %ProgramFiles(x86)%\\SOME_FOLDER \r\nstart xyz.bat \r\nexit");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }

        }

        // running our temp.bat file
        Runtime rt = Runtime.getRuntime();
        try {

            Process pr = rt.exec("cmd /c start \"\" \""+userprofile+"\\Desktop\\temp.bat" );
            pr.getOutputStream().close();
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);

        }
        // deleting our temp file
        File databl = new File(userprofile+"\\Desktop\\temp.bat");
        databl.delete();

以下は正常に機能しています。

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);

このコードは、パスC:/ folders / folderに存在する2つのcommands.batを実行します。

Runtime.getRuntime().exec("cd C:/folders/folder & call commands.bat");

@Ishaのanwser を展開するには、返された出力を取得するために以下を行うことができます(事後ではなく実行されたスクリプトのrea-ltime):

try {
    Process process = Runtime.getRuntime().exec("cmd /c start D:\\temp\\a.bat");
    System.out.println(process.getText());
} catch(IOException e) {
    e.printStackTrace();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top