Communicate with a windows batch file (or external program) from java
I know there are similar threads, and I have read them all. However none of them have been of any help.
I have this simple batch file:
@echo off
set /p UserInput=Enter a number:
echo Number was %UserInput%
I want to run this batch file from java, send the number to it and get the input.
I have a strange problem. I started the batch file using cmd /c, opened the input and output streams, but it still won't work. When I run a program, for example "cmd.exe", it returns the actual output that you get when you open a CMD window:
Microsoft Windows... Copyright (c) 2009 Microsoft Corporation. All rights reserved.
So at least the code is partially working. However it simply does not give me ANY output whatsoever when I use "cmd /c C:\\test.bat"
(where test.bat is a valid batch file).
This is the java code. What's wrong with it?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class Test {
private static BufferedReader bufIn;
private static BufferedWriter printOut;
private static Process p;
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime() ;
p = rt.exec("cmd.exe /c C:\\test.bat");
InputStream in = p.getInputStream() ;
OutputStream out = p.getOutputStream ();
bufIn = new BufferedReader(new InputStreamReader(in));
printOut = new BufferedWriter(new OutputStreamWriter(out));
int ch = 0;
ch = bufIn.read();
while (ch != 0)
{
System.out.print((char) ch);
ch = bufIn.read();
}
//send a command to
printOut.write("209");
printOut.flush();
while (ch != 0)
{
System.out.print((char) ch);
ch = bufIn.read();
}
//p.destroy() ;
}
}
I should be getting:
Please enter a number: Number was 209
Edit: I edited the code because it was apparently getting stuck at the readLine while there was no line :)
Anyway, I still have 开发者_如何学运维a problem. I'm getting:
Enter a number:
and nothing else, almost as if the output stream is not working at all.
Instead of using a PrintWriter, try an OutputStreamWriter wrapped in a BufferedWriter:
printOut = new BufferedWriter(new OutputStreamWriter(out));
Obviously you'll need to change printOut
to a BufferedWriter as well.
It also looks like you're flushing and printing in the wrong order to me, I'd do:
printOut.println("209");
printOut.flush();
As a side point, you can use readLine()
on BufferedReader rather than just read()
!
精彩评论