代码之家  ›  专栏  ›  技术社区  ›  John Johnson

Java runtime.exec未正确执行

  •  1
  • John Johnson  · 技术社区  · 11 年前

    我正在获取一个exe文件,必须在Windows Server 2008 R2上使用Java(版本6)执行该文件。现在有一个问题我不太明白。使用命令行执行文件时

    "C:\test.exe param1 param2" 
    

    它工作正常,但当我使用

    Process proc = Runtime.getRuntime().exec("C:\\test.exe param1 param2");
    proc.waitFor();
    

    我可以在windows任务管理器中看到test.exe,它开始运行(它创建了一个日志,说明了这一点),但之后它就不再做任何事情了。test.exe无休止地以0%运行,我必须手动终止进程。这样做之后,java程序继续

    proc.exitValue()
    

    是“1”,因此java认识到我已经终止了进程。我还尝试在批处理文件中编写命令行,并使用.exec()执行它,但没有任何改变。

    真正让我困惑的是,它可以通过windows命令行完美运行,但不能通过.exec()运行。有人知道是什么导致了这样的问题吗?或者更可能是test.exe导致了问题?

    致以最诚挚的问候

    编辑:在.exec中写入错误的路径

    3 回复  |  直到 11 年前
        1
  •  2
  •   fge    11 年前

    由于您的程序产生了大量输出,我的假设是,它无法写入标准输出(这是Linux下的管道,不适用于Windows)。

    试试看:

    final byte[] devnull = new byte[1024];
    
    final ProcessBuilder builder = new ProcessBuilder("C:\\test.exe", "param1", "param2")
        .redirectErrorStream(true);
    final Process p = builder.start();
    
    final InputStream stdout = process.getInputStream();
    
    // Purge stdout
    while (stdout.read[devnull] != -1);
    
    // Grab the process' exit code here
    
        2
  •  2
  •   Community CDub    8 年前

    正如fge在 https://stackoverflow.com/a/21903969 ,重要的是要消耗该过程产生的所有输出,不仅是在Linux上,而且在Windows上,不仅是标准输出,还有可能的错误。

    这方面的一般模式如下:

    private static void runCommand(String command) throws IOException
    {
        Process process = Runtime.getRuntime().exec(command);
        String errorMessage = 
            new String(toByteArray(process.getErrorStream()));
        String outputMessage = 
            new String(toByteArray(process.getInputStream()));
        int exitValue = 0;
        try
        {
            exitValue = process.waitFor();
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
        }
        System.out.println("Output message: "+outputMessage);
        System.out.println("Error message: "+errorMessage);
        System.out.println("Exit value: "+exitValue);
    }
    
    private static byte[] toByteArray(
        InputStream inputStream) throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buffer[] = new byte[8192];
        while (true)
        {
            int read = inputStream.read(buffer);
            if (read == -1)
            {
                break;
            }
            baos.write(buffer, 0, read);
        }
        return baos.toByteArray();
    }
    
        3
  •  0
  •   user207421    11 年前
    "C:\test.exe param1 param2"
    

    你有一个标签。试试看:

    "C:\\test.exe param1 param2"
    

    如果进程在stdout或stderr上生成任何输出,则需要使用它。否则它可能会阻塞。