empty ProcessBuilder InputStream - java

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);
}
}

Related

How do I run this python script in java?

I want to use this script in my java app: https://github.com/jcapona/amazon-wishlist-scraper.
I've looked around and I tried executing the script like so:
public static void main(String[] args) throws IOException {
String s = null;
Process p = Runtime.getRuntime().exec("python C:\\\\Users\\\\Home\\\\work\\\\test.py");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
while ((s=stdInput.readLine()) != null) {
System.out.println(s);
}
}
But I am not getting any output. What do I need to be able to run this specific script?
You can use like this :
String command = "python /c start python path\to\script\script.py>";
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = stdInput.readLine()) != null) {
System.out.println(line);
}
stdInput.close();
while ((line = stdErr.readLine()) != null) {
System.out.println(line);
}
stdErr.close();
p.waitFor();
System.out.println("Done.");
p.destroy();
Protip: Always copy your path from the file explorer tab
And since you are getting JSON response try GSON library to parse it.
And if you want to work heavily on python using java, try exploring Jython

Return output of Java Exec when providing array

I'm using java's exec() to run some *nix system commands, specifically a python script, but the problem is more general.
import java.io.*;
public class JRC {
public static void main(String args[]) {
String s[] = {"/bin/bash", "-c",
"source venv/bin/activate;python mergeExcel.py '/home/201811/'"};
try{
Process p = Runtime.getRuntime().exec(s);
}
catch (IOException e) {
System.out.println("exception: ");
e.printStackTrace();
}
}
}
The above code works, in accordance with the extent to which mergeExcel.py works.
However, I can't figure out how to print to stdout from python.
Here's my attempt, which only works if we exec() a simple string such as "ps -ef", rather than the array of strings i'm using.
try {
Process p = Runtime.getRuntime().exec(s);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
This actually results in a compilation error of incompatible types, java.lang.String instead of the required java.lang.String[].
How can I can print output from the source venv/.. command and the python command?
Thanks to the commenter, it's trivial to declare some temporary strings to print from stdout and stderr, though perhaps another user has a more elegant solution
try {
Process p = Runtime.getRuntime().exec(s);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
String stdi;
while ((stdi = stdInput.readLine()) != null) {
System.out.println(stdi);
}
String stderr;
while ((stderr = stdError.readLine()) != null) {
System.out.println(stderr);
}
System.exit(0);
}

I am not able to get expected output from run time exec

I executed this code:
Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
System.out.println(proc.toString());
String proc1 = proc.toString();
But I am not able to get the content of kafka_metrics.sh. Instead I am getting java.lang.UNIXProcess#5fd0d5ae as output. What should I include so that I can get the content of that file?
May this is what you are looking for.
Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
String s = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// 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) {
System.out.println(s);
}
You are printing the Process object.
to get the content of the executed process you need to take the input stream and pass that stream to the reader
Process process = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
InputStream is = process.getInputStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
br.lines().forEach(System.out::println);
}

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();
}

Implementing pipes in 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;
}

Categories