문제

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"});

이론적으로 당신은 이것을 테스트하지는 않았지만 이런 식으로 스콘을 실행할 수 있어야합니다.

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

편집 : Amara, 당신은 이것이 작동하지 않는다고 말합니다. 나열된 오류는 Windows 상자의 Cygwin 터미널에서 Java를 실행할 때 얻는 오류입니다. 이것이 당신이하는 일입니까? 그 문제는 Windows와 Cygwin이 다른 경로를 가지고 있다는 것입니다. 따라서 Java의 Windows 버전은 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 :/폴더/폴더에 존재하는 두 개의 명령을 실행합니다.

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

확장하기 위해 @Isha 's Anwser 실행 된 스크립트의 반환 된 출력 (Post-Facto가 아닌)을 얻기 위해 다음을 수행 할 수 있습니다.

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