使用Java应用程序打开.Bat

时间:2013-09-03 17:17:00

标签: cmd

我正在尝试使用java +打开CMD将代码应用于它以打开.jar,以便应用程序输出显示在.bat文件中。 谁能告诉我怎么做?

这是它得到的代码,它确实运行超出文件,但CMD没有显示。

btnTest.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String Bat = "C:"+File.separatorChar+"Users"+File.separatorChar+"Gebruiker"+File.separatorChar+"AppData"+File.separatorChar+"Local"+File.separatorChar+"Temp"+File.separatorChar+"hexT"+File.separatorChar+"run.bat";
            Runtime rt = Runtime.getRuntime();
            try {
                rt.exec(Bat);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

2 个答案:

答案 0 :(得分:0)

编辑:这对我有用:

String Bat = "C:\\app.bat";  //Try to use \\ as path seperator

try {
    Runtime.getRuntime().exec("cmd /c start " + Bat);
} catch (IOException e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

定义:

FileWriter writer;

然后在你的try / catch中执行以下操作:

    try {
        writer = new FileWriter("test.txt");
        Process child = rt.exec(Bat);
        InputStream input = child.getInputStream();
        BufferedInputStream buffer = new BufferedInputStream(input);
        BufferedReader commandResult = new BufferedReader(new InputStreamReader(buffer));
        String line = "";
        try {
            while ((line = commandResult.readLine()) != null) {
         writer.write(line + "\n");              
            }
        writer.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

这将逐行读取输出作为缓冲区并将其写入文本文件