简体   繁体   中英

running batch script in java program

In my eclipse project, I am trying to run system commands, I have collected them in a bash and put it in my project folder.

The java code part is:

public static int exportDBMainData(String DBName, String UserName,
            String Password, String FilePath) {

        // First
        String executeCmd = GraphEditor.class
                .getResource("/src/sau/se/editor/recover/semapExport.bat")
                + UserName + " " + Password + " " + DBName + " " + FilePath;
        Process runtimeProcess = null;
        try {
            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        int processComplete1 = -1;
        try {
            processComplete1 = runtimeProcess.waitFor();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        return processComplete1;
    }

When I run the application I get that error:

java.io.IOException: Cannot run program "nullroot": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)

What am I doing wrong?

UPDATE I fixed partly the problem, now I get:

java.io.IOException: Cannot run program "file:/F:/SEMAP_PROJECT/PHASE_1/ECLIPSE_KEPLER/Workspace/SeMap_Recover1.0/bin/sau/se/editor/recover/semapExport.bat": CreateProcess error=2, The system cannot find the file specified

With Runtime.exec you don't execute a shell command line but a real executable, optionally with arguments using a String[] cmdArray instad of a String. So you can't execute the bat line by line, but you can execute it directly with runtime exec:

 Runtime.getRuntime().exec(new String[]{
   "c:\\program files\\...\\semapExport.bat"
   ,UserName, Password,DBName,FilePath
 });

of course the bat file has to be a real file and not a resource in a jar.

The correct answer that I should call the script via a program, it can not call itself, so I fixed it like that and it has worked:

String executeCmd = "cmd /c start "
                + DBUtils.class
                        .getResource("/sau/se/editor/recover/semapExport.bat")
                + " " + UserName + " " + Password + " " + DBName + " "
                + FilePath;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM