Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

how to redirect stdin to java Runtime.exec?

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

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


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() 

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Exec returns a Process object to you.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...