How to execute a batch file to restart a service on windows by clicking a JMenuItem?

151 Views Asked by At

I am trying to create a UI and run a batch file that will restart a service running in the background just by clicking a menu item. I am able to make the menu and add the menu item just like so:

JMenu menu = new("menu");
JMenuItem restart_service= new JMenuItem("Restart service");
        menu .add(restart_service);

Then, I added a listener to the menu item to run the batch file:

    restart_service.addActionListener (new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent ae) {
            openWebPage(
                    "file://path to bat file/batchfile.bat");
        }
        public void openWebPage(String url) {
            try {
                java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
            } catch (java.io.IOException e) {
                System.out.println(e.getMessage());
            }
        }           
    });

However, everytime I try this, the cmd window pops up and prints "Access Denied". Although i changed the premission for the file to run without being admin. Not sure how to fix this or if there is a way to excute batch files as an admin by clciking a menu item. Any help would be appreciated.

1

There are 1 best solutions below

1
RRIL97 On

Try this.

try{    
Process mp = Runtime.getRuntime().exec("BAT LOC");
mp.waitFor();
}catch( Exception procRunException ){
}