首页 > 解决方案 > Java Process 没有输出到标准输出

问题描述

我正在从 java 进程(在 Windows 10,JDK 1.8 环境中)执行 mysql.exe,代码如下:

String command="D:\\SW\\MySQL_8\\bin\\mysql.exe --user=root --password=password";

ProcessBuilder pBuilder=new ProcessBuilder(command.split(" "));
pBuilder=pBuilder.redirectOutput(new File("D:\\workspaces\\cas\\CASCAppliance_Common\\out\\out.txt"));
pBuilder=pBuilder.redirectError(new File("D:\\workspaces\\cas\\CASCAppliance_Common\\out\\err.txt"));

Process p=pBuilder.start();
OutputStream os=p.getOutputStream();
PrintWriter writer=new PrintWriter(os);

如果我从命令行执行 mysql.exe,我会得到以下输出:

Microsoft Windows [Version 10.0.17134.228]
(c) 2018 Microsoft Corporation. All rights reserved.

D:\SW>cd MySQL_8\bin

D:\SW\MySQL_8\bin>mysql --user=root --password=password
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.11 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

我试图在错误流重定向后从进程中获取输入流,我只得到以下内容:

mysql: [Warning] Using a password on the command line interface can be insecure.

我也尝试将错误和标准输出重定向到文件,错误文件仍然包含上述文本,标准输出文件不包含任何内容。

另一方面,如果我执行 cmd.exe 并运行一个命令,比如“dir”,我将从进程的 InputStream 中获取所需的目录列表。

我的问题是,我做错了什么还是 mysql.exe 以无法从进程的输入流中获取上述输出的方式执行。

标签: javainputstreamprocessbuilder

解决方案


是的,这是关于 mysql 的。(编辑是来自@dave_thompson_085 的更新)

如果从交互式 shell 运行 mysql 但重定向输入和/或输出,它会抑制横幅、提示、表格装箱和“N 行(X 秒)”预告片。

请注意,即使没有提示,它仍然会读取 SQL 语句并执行它们,并显示任何结果集——尽管如果输出是一个管道,它会缓冲。相反,如果在终端上具有标准输入和标准输出的 Java 进程中,运行 mysql 继承它们,它具有完整的交互行为。


推荐阅读