Vin
Vin

Reputation: 41

how to get a batch file running using java

i have a batch file saved on my desktop and it serves the purpose of opening a calculator when executed. i want this batch file to function quite in the same way using java. i wrote the following command in netbeans

package runbatch;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Runbatch {

    public static void main(String[] args) {
        try {
            Runtime.getRuntime().exec("cmd /c hello.bat");
        } catch (IOException ex) {
            Logger.getLogger(Runbatch.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

although i get the build to be successful i am not getting the calculator opened up.

Upvotes: 2

Views: 96

Answers (4)

Mehdi
Mehdi

Reputation: 3763

ProcessBuilder is the safe and right way of doing this in java :

String[] command = new String[]{"cmd", "/c" ,"hello.bat"};
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(command);
processBuilder.start();

Upvotes: 0

Manu Zi
Manu Zi

Reputation: 2370

I prefer something like this:

String pathToExecutable = "C:/Program Files/calculator.exe";

try
{
    final List<String> processBuilderCommand = new ArrayList<String>();
    // Here you can add other commands too eg a bat or other exe
    processBuilderCommand.add(pathToExecutable);

    final ProcessBuilder processbuilder = new ProcessBuilder(processBuilderCommand);
    // Here you be able to add some additional infos to the process, some variables
    final Map<String, String> environment = processbuilder.environment();
    environment.put("AUTOBATCHNOPROGRESS", "no");

    processbuilder.inheritIO();
    final Process start = processbuilder.start();

    start.waitFor();
}
catch (IOException | InterruptedException e)
{
    LOGGER.error(e.getLocalizedMessage(), e);
}

i think it's a little bit flexibel then the others because you can add several and more then one execuable und you be able to add variables.

Upvotes: 0

Stack Underflow
Stack Underflow

Reputation: 2453

Try this:

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

Or you can execute your program without going through a batch file, like so:

Runtime.getRuntime().exec("cmd /c start java NameOfJavaFile");

Upvotes: 1

Rajesh Kolhapure
Rajesh Kolhapure

Reputation: 771

Add "start" argument and complete path of batch file: Runtime.getRuntime().exec("cmd /c start D:\sandbox\src\runbatch\hello.bat"); This works for me.

Upvotes: 0

Related Questions