Pregunta

En mi aplicación Java, quiero ejecutar un archivo por lotes que invoca " scons -Q implícita-deps-changed build \ file_load_type export \ file_load_type "

Parece que ni siquiera puedo ejecutar mi archivo por lotes. Estoy sin ideas.

Esto es lo que tengo en Java:

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

Anteriormente, tenía un archivo Python Sconscript que quería ejecutar, pero como no funcionó, decidí llamar al script a través de un archivo por lotes, pero ese método aún no ha tenido éxito.

¿Fue útil?

Solución

Los archivos por lotes no son un ejecutable. Necesitan una aplicación para ejecutarlos (es decir, cmd).

En UNIX, el archivo de script tiene shebang (#!) al inicio de un archivo para especificar el programa que lo ejecuta. Hacer doble clic en Windows es realizado por el Explorador de Windows. CreateProcess no sabe nada al respecto.

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

Nota: Con el comando start \ " \ " , se abrirá una ventana de comando separada con un título en blanco y allí se mostrará cualquier salida del archivo por lotes. También debería funcionar con solo `cmd / c build.bat " ;, en cuyo caso la salida se puede leer desde el subproceso en Java si se desea.

Otros consejos

A veces el tiempo del proceso de ejecución del subproceso es mayor que el tiempo del proceso de espera del subproceso JVM, suele suceder cuando el proceso que está invocando tarda un tiempo en procesarse, use el comando waitFor () de la siguiente manera:

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     

}

De esta manera, la JVM se detendrá hasta que se complete el proceso que está invocando antes de continuar con la pila de ejecución de subprocesos.

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

Para ejecutar archivos por lotes usando java, si te refieres a eso ...

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

Esto debería hacerlo.

ProcessBuilder es Java 5 / 6 formas de ejecutar procesos externos.

El ejecutable utilizado para ejecutar scripts por lotes es cmd.exe que utiliza el indicador / c para especificar el nombre del archivo por lotes que se ejecutará:

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

Teóricamente, también deberías poder ejecutar Scons de esta manera, aunque no he probado esto:

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

EDITAR: Amara, dices que esto no está funcionando. El error que enumeró es el error que obtendría al ejecutar Java desde un terminal Cygwin en un cuadro de Windows; es esto lo que estas haciendo? El problema con eso es que Windows y Cygwin tienen rutas diferentes, por lo que la versión de Windows de Java no encontrará los scons ejecutables en su ruta Cygwin. Puedo explicarte más si esto resulta ser tu problema.

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

probado con jdk1.5 y jdk1.6

Esto funcionó bien para mí, espero que también ayude a otros. Para conseguir esto he luchado más días. :(

Tuve el mismo problema. Sin embargo, a veces CMD no pudo ejecutar mis archivos. Por eso creo un temp.bat en mi escritorio, luego este temp.bat ejecutará mi archivo y luego el archivo temporal será eliminado.

Sé que este es un código más grande, sin embargo, funcionó para mí en el 100% cuando incluso Runtime.getRuntime (). exec () falló.

// 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();

Lo siguiente está funcionando bien:

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

Este código ejecutará dos comandos.bat que existen en la ruta C: / carpetas / carpeta.

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

Para expandir en @ Isha's anwser solo puede hacer lo siguiente para obtener el resultado devuelto (post-facto no en rea-ltime) del script que se ejecutó:

try {
    Process process = Runtime.getRuntime().exec("cmd /c start D:\\temp\\a.bat");
    System.out.println(process.getText());
} catch(IOException e) {
    e.printStackTrace();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top