【问题标题】:Start/Stop Windows Service with buttons使用按钮启动/停止 Windows 服务
【发布时间】:2014-07-01 01:23:11
【问题描述】:

我正在创建一个非常简单的应用程序来停止和启动 Windows 服务。我需要它有一个GUI界面,所以我选择了JAVA。如果您知道更简单的语言,请告诉我。作为一个示例,我希望它停止并启动打印后台处理程序。我已经使用 NetBeans 创建了 GUI 界面,但我需要有关编码部分的帮助。请帮忙。谢谢!

package MyServiceToolPKG;
public class MyServiceToolGUI extends javax.swing.JFrame {

/**
 * Creates new form MyServiceToolGUI
 */
public MyServiceToolGUI() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    StartButton = new javax.swing.JButton();
    StopButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    StartButton.setText("Start");
    StartButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            StartButtonActionPerformed(evt);
        }
    });

    StopButton.setText("Stop");
    StopButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            StopButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(StopButton)
                .addComponent(StartButton))
            .addContainerGap(26, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(StartButton)
            .addGap(18, 18, 18)
            .addComponent(StopButton)
            .addContainerGap(22, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void StartButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
}                                           

private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
}                                          

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MyServiceToolGUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton StartButton;
private javax.swing.JButton StopButton;
// End of variables declaration                   

}

更新代码:

private void StartButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    StartSpooler();
}                                           

private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    StopSpooler();
}
private void StopSpooler() {
    String[] args = {"stop"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

private void StartSpooler() {
    String[] args = {"start"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

谢谢大家!

这是我的代码:

private void StopSpooler() {
    String[] args = {"stop"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

private void StartSpooler() {
    String[] args = {"start"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

我创建了一个批处理文件,我以管理员身份运行并调用 jar 应用程序

@echo off
java.exe -jar C:\test\MyServiceTool.jar
pause

【问题讨论】:

  • "... but I need help with the coding part." -- 并不是一个真正的问题。请提出一个可回答的具体问题。
  • 如何停止和启动 Windows 服务?

标签: java swing processbuilder


【解决方案1】:

在 Windows 命令行中: 您需要管理员权限才能执行此操作。 停止 Windows 服务:

net stop Spooler

要启动 Windows 服务:

net start Spooler

在 Java 中,您可以使用以下命令执行 dos 命令:

try {
        Runtime.getRuntime().exec("net stop spooler");
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
    }

【讨论】:

  • ProcessBuilder 会是更好的解决方案
  • 好的,我使用了 ProcessBuilder,但我得到了拒绝访问。有什么建议吗?
  • 运行:[SC] OpenService FAILED 5:访问被拒绝。 [SC] StartService: OpenService FAILED 5: 访问被拒绝。
  • FAILED 5 表示程序未在管理员模式下运行。
  • 如何以管理员身份运行我的 java 程序?右键单击时没有选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多