2

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.

4 Answers 4

1

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");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.