How do I run a batch file from my Java Application?

后端 未结 11 1687
情书的邮戳
情书的邮戳 2020-11-22 00:42

In my Java application, I want to run a batch file that calls \"scons -Q implicit-deps-changed build\\file_load_type export\\file_load_type\"

It seems t

11条回答
  •  抹茶落季
    2020-11-22 01:20

    I had the same issue. However sometimes CMD failed to run my files. That's why i create a temp.bat on my desktop, next this temp.bat is going to run my file, and next the temp file is going to be deleted.

    I know this is a bigger code, however worked for me in 100% when even Runtime.getRuntime().exec() failed.

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

提交回复
热议问题