import java.io.File; import java.io.OutputStreamWriter; class Demo { // 1. If the file is on disk, this is the easiest: static void send1() { try { ProcessBuilder pb = new ProcessBuilder("mycmd", "arg1", "arg2"); pb.redirectInput(new File("/tmp/myfile.txt")); Process proc = pb.start(); proc.waitFor(); } catch (Exception ex) { System.err.println("Could not run because " + ex.getMessage()); } } // 2. If want you want to send is in your Java code: static void send2() { final String cmd = "mycmd"; 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) { System.err.println("Could not run because " + ex.getMessage()); } } public static final void main(String []args) { send1(); send2(); } }
Programming Tips - Java: How to send a file to a command
Date: 2013apr7
Update: 2025oct8
Language: Java
Keywords: redirect, pipe
Q. Java: How to send a file to a command
A. There are two ways as shown in this full example: