Domanda

Nella mia applicazione Java, voglio eseguire un file batch che chiama " scons -Q implicit-deps-changed build \ file_load_type export \ file_load_type "

Sembra che non riesca nemmeno a eseguire il mio file batch. Sono senza idee.

Questo è quello che ho in Java:

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

In precedenza, avevo un file Python Sconscript che volevo eseguire ma dato che non funzionava, ho deciso che avrei chiamato lo script tramite un file batch ma quel metodo non ha ancora avuto successo.

È stato utile?

Soluzione

I file batch non sono eseguibili. Hanno bisogno di un'applicazione per eseguirli (ad esempio cmd).

Su UNIX, il file di script ha shebang (#!) all'inizio di un file per specificare il programma che lo esegue. Il doppio clic in Windows viene eseguito da Esplora risorse. CreateProcess non ne sa nulla.

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

Nota: con il comando start \ " \ " , verrà aperta una finestra di comando separata con un titolo vuoto e qualsiasi output dal file batch verrà visualizzato lì. Dovrebbe funzionare anche solo con `cmd / c build.bat " ;, nel qual caso l'output può essere letto dal processo secondario in Java se lo si desidera.

Altri suggerimenti

A volte il tempo del processo di esecuzione del thread è superiore al tempo del processo di attesa del thread JVM, si verifica quando il processo che si sta invocando richiede del tempo per essere elaborato, utilizzare il comando waitFor () come segue:

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     

}

In questo modo JVM si fermerà fino a quando il processo che stai invocando non viene completato prima di continuare con lo stack di esecuzione del thread.

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

Per eseguire file batch usando java se stai parlando ...

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

Questo dovrebbe farlo.

ProcessBuilder è Java 5 / 6 modi per eseguire processi esterni.

L'eseguibile utilizzato per eseguire script batch è cmd.exe che utilizza il flag / c per specificare il nome del file batch da eseguire:

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

Teoricamente dovresti anche essere in grado di eseguire Scons in questo modo, anche se non l'ho provato:

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

EDIT: Amara, dici che non funziona. L'errore che hai elencato è l'errore che otterrai quando esegui Java da un terminale Cygwin su una finestra di Windows; è questo che stai facendo? Il problema è che Windows e Cygwin hanno percorsi diversi, quindi la versione Windows di Java non troverà gli scons eseguibili sul tuo percorso Cygwin. Posso spiegare ulteriormente se questo risulta essere il tuo problema.

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

testato con jdk1.5 e jdk1.6

Stava funzionando bene per me, spero che aiuti anche gli altri. per ottenere questo ho lottato più giorni. : (

Ho avuto lo stesso problema. Tuttavia a volte CMD non è riuscito a eseguire i miei file. Ecco perché creo un temp.bat sul mio desktop, quindi questo temp.bat eseguirà il mio file e successivamente il file temporaneo verrà eliminato.

So che questo è un codice più grande, tuttavia ha funzionato per me al 100% quando anche Runtime.getRuntime (). exec () non è riuscito.

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

Di seguito funziona correttamente:

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

Questo codice eseguirà due comandi.bat presenti nel percorso C: / cartelle / cartella.

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

Per espandere su @ Isha's anwser potresti semplicemente fare quanto segue per ottenere l'output restituito (post-facto non in rea-ltime) dello script eseguito:

try {
    Process process = Runtime.getRuntime().exec("cmd /c start D:\\temp\\a.bat");
    System.out.println(process.getText());
} catch(IOException e) {
    e.printStackTrace();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top