我有一个使用ProcessBuilder创建进程并执行外部程序(.jar)的程序。外部进程应该从stdin接收一个String,将它们的字符转换为大写或大写,并发送转换后的String thru stdout。主进程从键盘读取String,使用流将其发送到外部进程并打印外部进程的输出。但是,当我运行主程序时,它似乎陷入外部进程试图从其标准输入读取数据。 我怎么能解决这个问题,有什么建议吗?还有另一种方法可以实现这一点(将String作为执行外部程序的命令的参数发送)但我需要使用流来完成。
这是主程序的代码:
public static void main(String[] args) throws IOException {
String str = JOptionPane.showInputDialog("Insert a String");
String[] cmd = {"java", "-jar",
"ejecutable/Transformador2.jar"};
Process process = new ProcessBuilder(cmd).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = process.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(str);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
以下是外部流程的代码:
public static void main(String[] args) throws IOException {
String str, strConv="";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
char c;
str = input.readLine();
for (int i=0; i<str.length(); i++) {
c = str.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
if (c == Character.toUpperCase(c))
strConv += Character.toLowerCase(c);
else if (c == Character.toLowerCase(c))
strConv += Character.toUpperCase(c);
}
}
System.out.print(strConv);
}
提前致谢。
答案 0 :(得分:0)
已解决:在将字符串发送到外部进程后,需要关闭输出流。
bw.write(str);
bw.close();
答案 1 :(得分:0)
确切地说,您需要bw.flush()
将数据从缓冲区推送到基础流。 bw.close()
隐式刷新缓冲区。这就是它工作的原因。