【问题标题】:How to execute cmd commands via Java swing如何通过 Java swing 执行 cmd 命令
【发布时间】:2012-11-05 07:41:08
【问题描述】:

我有一个文件要打印,我想通过 java swing 给他发送一个自定义水印。 我有 2 个文件 NewJFrame.java 和 Test.java

package test;

import java.io.IOException;
import java.io.OutputStream;

/**
 *
 * @author shaharnakash
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        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() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("whater mark name");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setText("submit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(30, 30, 30)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 251, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .add(17, 17, 17)
                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 206, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(41, 41, 41)
                        .add(jLabel1))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 57, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(112, 112, 112)
                .add(jButton1)
                .addContainerGap(96, Short.MAX_VALUE))
        );

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

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String value;
        value = jTextField1.getText();
         try{
            String command = "cmd /c start cmd.exe";
            Process child = Runtime.getRuntime().exec(command);

            OutputStream out = child.getOutputStream();
            out.write("C:/PDF>pdfprint.exe -printer 'docPrint' -firstpage 1 -lastpage 1 -wtext 'value' -wo 100 -wa 50 -wf 'Arial' C:/readme.pdf".getBytes());
                out.close();
        }catch(IOException e){

        }
    }                                        

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

以及执行程序的主要java类Test.java

    package test;

/**
 *
 * @author shaharnakash
 */
public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
}

想法是在文本字段中插入一个值,然后单击提交按钮,它将执行 cmd 命令

C:/PDF>pdfprint.exe -printer 'docPrint' -firstpage 1 -lastpage 1 -wtext 'value' -wo 100 -wa 50 -wf 'Arial' C:/readme.pdf

当我执行程序时,它将打开 cmd 并且不会将文件发送到打印机

注意:草稿是水印变化

我更改为 Process child = Runtime.getRuntime().exec("\"PDF\pdfprint.exe -printer docPrint -firstpage 1 -lastpage 1 -wtext "+value+" -wo 100 -wa 50 -wf Arial C :\readme.pdf");

我还是没有工作

【问题讨论】:

    标签: java swing cmd runtime.exec processbuilder


    【解决方案1】:

    就我个人而言,我会使用ProcessBuilder,如果没有其他原因,它会大大减少使用Process 所涉及的复杂性。

    ProcessBuilder pb = new ProcessBuilder("pdfprint.exe", "-printer", "'docPrint'", "-firstpage", "1", "-lastpage", "1", "-wtext", "'value'", "-wo", "100", "-wa", "50", "-wf", "'Arial'", "C:/readme.pdf");
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStream is = p.getInputStream();
    int inInt = -1;
    while ((inInt = is.read()) != -1) {
        System.out.print((char)inInt);
    }
    

    现在,这是一个块调用,这意味着如果您在 UI 的上下文(也称为事件调度线程)中执行此操作,UI 将显示为挂起,直到外部进程完成运行。

    在这种情况下你应该调用执行后面的命令。可能最简单的方法是使用SwingWorker

    public class ExeWorker extends SwingWorker<String, String> {
        public String doInBackground() {
            // Execute command here...
            // Depending on what you want to return, setup a return value
            // This could an error string or the path to the output file for example...
    
           return result;
        }
    
        public void done() {
            // Back on the EDT, update the UI ;)
        }
    }
    

    阅读Concurrency in Swing了解更多详情

    【讨论】:

      【解决方案2】:

      使用Runtime.getRuntime().exec() 方法。谷歌关于它的不同变体。

      【讨论】:

      • 我不明白如何在我的命令上实现它我在这里看到了答案link