Dave's Brain

Browse - Programming Tips - How can I send a file to a command?

Date: 2013spr7
Language: Java

Keywords: redirect, pipe

Q.  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) { }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.