在Java中发出命令提示符命令

时间:2013-07-09 21:58:48

标签: java cmd

我试过了:

Process rt = Runtime.getRuntime().exec("cmd /c start C:\\Users\\spacitron\\batchfiles\\mybatch.bat");

但所有这一切都会在屏幕上弹出命令提示符。

1 个答案:

答案 0 :(得分:1)

至于你的特定问题,我怀疑命令行参数会被破坏。这实际上是Runtime#exec的一个常见问题。

相反,我建议您改用ProcessBuilder。它对命令行参数更加宽容,并且更好地处理空格等事情。

例如......

<强> MyBatch.bat

@echo off

echo这是一条测试消息

<强> RunBatchCommand

import java.io.IOException;
import java.io.InputStream;

public class RunBatchCommand {

    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder("cmd", "start", "/c", "MyBatch.bat");
        pb.redirectError();
        try {
            Process p = pb.start();
            InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream());
            new Thread(isc).start();
            int exitCode = p.waitFor();

            System.out.println("Command exited with " + exitCode);
            if (isc.getCause() == null) {
                System.out.println(isc.getOutput());
            } else {
                isc.getCause().printStackTrace();
            }

        } catch (IOException | InterruptedException exp) {
            exp.printStackTrace();
        }

    }

    public static class InputStreamConsumer implements Runnable {

        private InputStream is;
        private StringBuilder sb;
        private IOException cause;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
            sb = new StringBuilder(128);
        }

        @Override
        public void run() {
            try {
                int in = -1;
                while ((in = is.read()) != -1) {
                    sb.append((char) in);
                    System.out.print((char) in);
                }
            } catch (IOException exp) {
                cause = exp;
                exp.printStackTrace();
            }
        }

        protected String getOutput() {
            return sb.toString();
        }

        public IOException getCause() {
            return cause;
        }

    }
}

哪个生成...

This is a test message
Command exited with 0
This is a test message