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

查看:206
本文介绍了如何将stdin重定向到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\/bin\mysql.exe -u <userName> -p <password> < scripts\create_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读取文件scripts\create_tables.sql并将内容传递给prcess的输出流。我期待Process将数据传递给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 "scripts\create_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.

进程有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.

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

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