简体   繁体   English

如何通过单击 JMenuItem 执行批处理文件以在 Windows 上重新启动服务?

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

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.我正在尝试创建一个 UI 并运行一个批处理文件,该文件将通过单击菜单项重新启动在后台运行的服务。 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".但是,每次尝试此操作时,都会弹出 cmd 窗口并打印“拒绝访问”。 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.任何帮助,将不胜感激。

Try this.尝试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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