Date: 2013apr7
Language: Java
Keywords: redirect, pipe
Q. Java: How can I send a file to a command?
A. There are two ways.
1. If the file is on disk, this is the easiest:
try {
ProcessBuilder pb = new ProcessBuilder("mycmd", "arg1", "arg2");
pb.redirectInput(new File("/tmp/myfile.txt"));
Process proc = pb.start();
proc.waitFor();
} catch(Exception ex) {
}
2. If want you want to send is in your Java code:
try {
Process proc = Runtime.getRuntime().exec(cmd);
OutputStreamWriter os = new OutputStreamWriter(proc.getOutputStream());
os.write("what you want to send");
os.close();
proc.waitFor();
} catch(Exception ex) {
}