如何使用java运行批处理文件

时间:2015-03-31 15:29:48

标签: java dos

我想使用java程序运行批处理文件,当我双击.bat文件时,它要求我输入'D',之后它在C盘中创建一些文件夹,下面是.bat的内容文件:

xcopy "data" "C:\data" /S
xcopy "rapid" "C:\rapid" /S
subst x: /D
subst x: C:\

我的Java代码如下:

try {
            //C:\Desktop\Speed\view_R36_WD_Release\RAPID\switchToLive.Bat
            String cmds[] = {"C:\\Users\\608521747\\Desktop\\Speed\\view_R36_WD_Release\\RAPID\\switchToDev.bat"};
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(cmds);
            process.getOutputStream().close();
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
            BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
            String strLine = "";
            while ((strLine = bufferedrReader.readLine()) != null) {
                System.out.println(strLine);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } 

它没有给我任何错误,但它既没有要求我输入任何值也没有创建任何文件夹。

我想知道在java代码中我需要做什么,这样它就会要求我输入'D',然后.bat文件应该继续正常流程。

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您的代码需要指定执行.bat文件的程序。 通过以下修复开始缩小范围。

p = run.exec("cmd.exe /c " + cmds);

还可以尝试this link for similar code之前在此处回答的类似问题。

答案 1 :(得分:0)

批处理文件不是可执行文件。因此,您需要运行cmd.exe并将批处理文件作为参数传递。

请参阅此帖子 - 它解决了同一问题并提供了一个很好的解决方案 - How do I run a batch file from my Java Application?