Open ffplay & execute command with ProcessBuilder not working - java

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

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

Failed to execute child process “'scriptName.sh” (No such file or directory)

String command= "/usr/bin/gnome-terminal.wrapper -e 'startDemonstrator.sh; bash'";
File workDir = new File("/home/malju/Desktop");
Process pr = Runtime.getRuntime().exec(command, null, workDir);
After I execute this line of code I get the error above. My script is located in the Desktop folder. I already tried adding ./startDemonstrator and full path. I always get the error above. What can be the reason be?
I am just trying to open a sh script after the terminal is opened.
First try like below:-
String command= "/home/malju/Desktop/startDemonstrator.sh";
Process pr = Runtime.getRuntime().exec(command);
p.waitFor();
If still not working try with below approach with ProcessBuilder.
String result = "";
String[] command = {"/home/malju/Desktop/startDemonstrator.sh"};
ProcessBuilder process = new ProcessBuilder(command);
Process p ;
try {
p = process.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
result = builder.toString();
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}

Running cmd as administrator in Java

I'm trying to write a function that has the name of a service as parameter. The problem is that i can only start and stop a service in cmd ( in windows) only if i run it as administrator. How can i run cmd in java as administrator? Can you please help me?? Thanks
public String stop(String name) {
try {
List<String> command = new ArrayList<String>();
command.add("cmd.exe");
command.add("/c");
command.add("runas");
command.add("/user:Administrator");
command.add("\"net");
command.add("stop");
command.add(name + "\"");
System.out.println(command);
Process servicesProcess = new ProcessBuilder(command).start();
InputStream input = servicesProcess.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
StringBuffer queryResult = new StringBuffer();
while ((line = reader.readLine()) != null) {
queryResult.append(line);
}
reader.close();
servicesProcess.destroy();
System.out.println(queryResult.toString());
if (queryResult.toString().toLowerCase().contains("failed") || queryResult.toString().toLowerCase().contains("error")) {
return "Failed #stop";
}
System.out.println("Stop service completed succesfully!");
return "Succes #stop";
} catch (IOException e) {
return "Failed #stop";
}
}
I also tried with this and still doesn't work
List<String> command = new ArrayList<String>();
command.add("cmd.exe");
command.add("/c");
command.add("Powrprof.dll");
command.add(",");
command.add("SetSuspendState");
command.add("net");
command.add("stop");
command.add(name);
System.out.println(command);
Process servicesProcess = new ProcessBuilder(command).start();

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

Categories