-1

我试过这个:

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

但所发生的只是命令提示符在屏幕上弹出。

4

1 回答 1

1

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

相反,我建议您ProcessBuilder改用。命令行参数更加宽容,并且可以更好地处理诸如空格之类的事情。

例如...

我的批处理文件

@echo 关闭

echo 这是一条测试消息

运行批处理命令

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
于 2013-07-10T00:24:36.643 回答