How to execute cmd commands via Java swing

孤街浪徒 提交于 2019-12-06 09:16:43

Personally, I'd use ProcessBuilder, if for no other reason, it reduces a lot of the complexity involved with working with 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);
}

Now, this is a block calling, meaning if you execute this within the context of your UI (AKA The Event Dispatching Thread), the UI will appear to hang until the external process has finished running.

In this case you should call execute the command in the back. Probably the simplest approach would be to use a 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 ;)
    }
}

Have a read of Concurrency in Swing for more details

use Runtime.getRuntime().exec() method. Google about its different variants.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!