如何将标准输入重定向到 java Runtime.exec? [英] how to redirect stdin to java Runtime.exec?

查看:34
本文介绍了如何将标准输入重定向到 java Runtime.exec?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Java 的 Runtime.exec 方法执行一些 sql 脚本.我打算调用 mysql.exe/mysql.sh 并将脚本文件重定向到这个进程.从命令提示符我可以运行命令

I want to execute some sql scripts using Java's Runtime.exec method. I intend to invoke mysql.exe / mysql.sh and redirect the script file to this process. From the command prompt I can run the command

<mysqInstallDir/binmysql.exe -u <userName> -p <password> < scriptscreate_tables.sql

我可以使用 Runtime.exec 调用 mysql.exe 但如何将数据从 sql 文件重定向到 mysql.exe ?

I can invoke mysql.exe using Runtime.exec but how do I redirect data from sql file to mysql.exe ?

我阅读了 http 中的文章://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4 并使用 StreamGobbler 机制获取错误和输出流.没有问题.问题在于使用 BufferedReader 读取文件scriptscreate_tables.sql"并将内容传递给 prcess 的输出流.我期待进程将数据传递给 mysql.exe.但我看到只有第一行是从这个 sql 文件中读取的.

I read the article in http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4 and used the StreamGobbler mechanism to get the error and output streams. No problem there. The problem comes in reading the file "scriptscreate_tables.sql" using BufferedReader and passing the contents to prcess's outputstream. I was expecting the Process to pass the data to the mysql.exe. But I see that only the first line is read from this sql file.

OutputStream outputstream = proc.getOutputStream();
OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
  while ( (line = br.readLine()) != null)
  {
bufferedwriter.write(line);
bufferedwriter.flush();
System.out.println(line);
  }
  bufferedwriter.flush();
  bufferedwriter.close();
  proc.waitFor() 

当我这样做时,我看到只有 create_tables.sql 中的第一行被执行.该进程的退出代码为 0,并且没有其他错误或输出.

When I do this I see that only the first line in create_tables.sql is executed. The exit code for the process is 0 and there is other no error or output.

推荐答案

Exec 返回一个 Process 对象给你.

Exec returns a Process object to you.

Process 有 getInputStream 和 getOutputStream 方法.

Process has getInputStream and getOutputStream methods.

只需使用它们来获取输入流并开始将字节推入其中.不要忘记读取输出流,否则进程可能会阻塞.

Just use those to grab the input stream and start shoving bytes into it. Don't forget to read the output stream or the process may block.

这篇关于如何将标准输入重定向到 java Runtime.exec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆