我在Windows8.1操作系统下工作。在其中,我有一个名为.bat test.bat的文件,它只执行一个回显命令:
echo "123" > output.txt每当我从命令行(cmd.exe)运行该文件时,它都会创建一个名为output.txt的文本文件,其中将写入"123“(我假设该文件并非每次调用.bat时都存在,以实现简单性)。
每次我从命令行调用它时,.bat都会运行OK,但是当我试图从Java源代码调用它时,.bat不会执行,即使代码运行正常(或者看起来是这样,因为没有显示警告或错误代码)。
我的Java源代码如下:
    import java.io.*;
    import java.util.*;
    public class HelloWorld {
        public static void main(String[] args) throws InterruptedException{
        try
        {
            List<String> command_args = Arrays.asList("cmd.exe", null , " "test.
            File dir =  new File("C:\\Users\\Administrador\\workspace\\test\\src\\test");
            String[] files = dir.list();
            Runtime.getRuntime().exec("cmd /c test.bat", null, new File("C:\\Users\\Administrador\\workspace\\test\\src\\test"));
            if( files.length == 0 )
            {
                System.out.println("Empty dir");
            }
            else
            {
                for( String f: files )
                {
                    System.out.println(f);      
                }       
            }
            ProcessBuilder pb = new ProcessBuilder( command_args );
            pb.directory(dir);
            Process proc = pb.start();
            //int error = proc.waitFor();
        }
        catch( IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
}该文件名为HelloWorld.java,可在路由C:\Users\Administrador\workspace\test\src\test.中找到。代码的一些行用于列出变量dir引用的目录的内容,该变量实际上指向正确的目录,因为代码的输出显示目录内的文件( HelloWorld.java和test.bat )。
如果我运行该代码,它将正确地打印目录内容,并且似乎也会执行100%的代码,但是每次运行该代码时都没有创建output.txt文件。我尝试用两种不同的方式从.bat运行ProcessBuilder,使用ProcessBuilder和直接从运行时运行,但这两种方法都没有达到预期的结果。
您知道它是否可以从Java中完全运行这类.bat,或者我是否需要为此使用一个特定的库?
提前谢谢。
发布于 2016-10-25 22:09:35
代码i show.it运行良好。
最重要的是你应该读inputStream,如果你不读,它可能不会成功。
waitFor()使主进程运行,直到.bat工作完成。
echo helloworld >>f:/2.txt 
exit在f:/hello.bat中
Process p;
    String cmd="cmd /c start f:\\hello.bat";
    try {
        p = Runtime.getRuntime().exec(cmd);
        InputStream in = p.getInputStream();
        int c;
        while ((c = in.read()) != -1) {
                System.out.print(c);
        }
        in.close();
        try {
                p.waitFor();
        } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        System.out.println("done");
    } catch (IOException e) {
        System.out.println("play show error");
    }https://stackoverflow.com/questions/40249229
复制相似问题