Implementing pipes in Java - java

Need advise on how to implement pipes in Java. Eg,
echo "test"|wc
I need to show results of the above pipe example.
I have tried this:
public class myRunner {
private static final String[] cmd = new String[] {"wc"};
public static void main(String[] args){
try {
ProcessBuilder pb = new ProcessBuilder( cmd );
pb.redirectErrorStream(true);
Process process = pb.start();
OutputStream os = process.getOutputStream();
os.write("echo test".getBytes() );
os.close();
}catch (IOException e){
e.printStackTrace();
}
How can I view the output of wc output?
I believe another one of the library i can use is PipedInputStream/PipedOutputStream. Can anyone show an example on how to use it? Am quite confused. thanks

How can I view the output of wc output?
By consuming the Process's output, via Process.getInputStream(), and reading from it.

public ArrayList<String> executorPiped(String[] cmd, String outputOld){
String s=null;
ArrayList<String> out=new ArrayList<String>();
try {
ProcessBuilder pb = new ProcessBuilder( cmd );
pb.redirectErrorStream(true);
Process p = pb.start();
OutputStream os = p.getOutputStream();
os.write(outputOld.getBytes());
os.close();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
out.add(s);
}
}catch (IOException io){
}
return out;
}

Related

Save Python console output to Java variable

I have problem with saving python script's output to java variable. My code looks like...
Python script:
def main(argv):
filepath = argv[1]
...
output = results.get_forecast(14).predicted_mean.to_json()
print(output)
if __name__ == "__main__":
main(sys.argv)
And it works - results are printed to console - everything's fine.
My Java code:
ProcessBuilder pb = new ProcessBuilder("python", "-u",
"path/to/script.py", args_filepath).inheritIO();
try {
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder predictionString = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
predictionString.append(line);
}
int exitCode = p.waitFor();
System.out.println("VALUE: " + predictionString.toString());
br.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
That part also works... I mean it works in a way that it executes the python's code, writes output to console, but it doesn't save the output string to the predictionString.
Use redirectErrorStream method to capturing output stream.
ProcessBuilder pb = new ProcessBuilder("python", "-u",
"path/to/script.py", args_filepath)
.redirectErrorStream(true);
instead of
ProcessBuilder pb = new ProcessBuilder("python", "-u",
"path/to/script.py", args_filepath).inheritIO();

Open ffplay & execute command with ProcessBuilder not working

I was tried to use ProcessBuilder for open ffplay.exe and execute command into ffplay. However it is unsuccessful. How could I do that?
Code:
ProcessBuilder pb = new ProcessBuilder();
pb.command("C:\\Windows\\System32\\cmd.exe", "/c",
"C:\\ffmpeg\\bin\\ffplay.exe", "tcp://192.168.1.1:5555");
pb.start();
Try using Runtime.getRuntime().exec() and doing like this :-
String[] command = {"ffplay.exe", "tcp://192.168.1.1:5555"}; // add in String array in sequence, the commands to execute
Process process = Runtime.getRuntime().exec(String[] options, null, new File("C:\\ffmpeg\\bin"));
int returnVal = process.waitFor(); // should return 0 for correct execution
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line); //check for the inputstream & see the output here
}
reader.close();
} catch (final Exception e) {
e.printStackTrace();
}

How do I redirect from console (including error and output) to a file in Java?

package online_test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class cmdline_test {
/**
* #param args
*/
public static void main(String[] args) {
try {
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/c";
command[2] = "c: && dir && cd snap";
Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Error;
while ((Error = stdError.readLine()) != null) {
System.out.println(Error);
}
while ((Error = stdInput.readLine()) != null) {
System.out.println(Error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I run this code, I get the output of this code printed to the console. However, I wasn't able to figure out how to copy that output to a file. How would I go about doing so?
Use a ProcessBuilder:
final File outputFile = Paths.get("somefile.txt").toFile();
final ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "whatever")
.redirectOutput(outputFile)
.redirectErrorStream(true);
final Process p = pb.start();
// etc
Read the javadoc carefully; there is a lot more you can do with it (affecting the environment, changing the working directory etc).
Also, do you really need to go through an interpreter at all?
A more simple solution is to change the outputstream of System.out to a file. This way, every time you invoke System.out.println(...) it will write to said file. Add this to the start of your program:
File file =
new File("somefile.log");
PrintStream printStream = null;
try {
printStream = new PrintStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.setOut(printStream);
You can do the same for System.err for printing errors to a different file.

empty ProcessBuilder InputStream

I have some problems using the java ProcessBuilder.
I want to get my gpg keys, so I use the following code:
ProcessBuilder builder = new ProcessBuilder("C:\\[path]\\GnuPG\\pub\\gpg.exe", "--list-keys");
//builder.directory(new File("C:\\[path]\\GnuPG\\pub\\"));
Process process = builder.start();
Scanner s = new Scanner(process.getInputStream()).useDelimiter("\\Z");
System.out.println(s.next());
s.close();
But I always get a NoSuchElementException when executing s.next().
If I use the gpg command "-h", I always get the expected output.
If I change the Constructor call to
new ProcessBuilder("cmd", "/c", "C:\\[path]\\GnuPG\\pub\\gpg.exe", "--list-keys");
it sometimes works. But most times it doesn´t.
WHY? Can anyone help? THANKS!!
Try this-
Test test = new Test();
List<String> commands = new ArrayList<String>();
commands.add("C:\\[path]\\GnuPG\\pub\\gpg.exe");
commands.add("--list-keys");
test.doCommand(commands);
}
public void doCommand(List<String> command)
throws IOException
{
String s = null;
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader
(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader
(process.getErrorStream()));
StringBuffer start= new StringBuffer();
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{
start.append(s);
System.out.println(s.toString());
}
stdInput.close();
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
{
start.append(s);
System.out.println(s);
}
}

BufferedReader and process.getOutputStream()

I'm simply trying to execute a process in Java, so
Runtime runtime = Runtime.getRuntime();
this.process = null;
try {
this.process = runtime.exec(new String[] {
properties.getPropertyStr("ffmpegExecutable", "/usr/bin/ffmpeg"),
"-i", this.streamEntry.getSource(),
"-vcodec", "copy",
"-acodec", "copy",
this.streamEntry.getDestination()
});
} catch (IOException e) {
e.printStackTrace();
return;
}
BufferedReader stdout = new BufferedReader(???process.getOutputStream());
I simply want to be able to read the output of the process line by line. How do I do this?
BufferedReader is; // reader for output of process
String line;
// getInputStream gives an Input stream connected to
// the process standard output. Just use it to make
// a BufferedReader to readLine() what the program writes out.
is = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = is.readLine()) != null)
System.out.println(line);
BufferedReader in
= new BufferedReader(new InputStreamReader(process.getInputStream()));

Categories