I am using ProcessBuilder to execute git command inside my java application. The output string is correct when the command is "git status" or "git branch", however the output was empty when the command is "git clone". I wonder how can I get the output string of "git clone". Thanks in advance.
try {
ProcessBuilder pb = new ProcessBuilder("git", "clone", "address");
Process pr = pb.start();
BufferedReader buf = new BufferReader(new InputStreamReader(pr.getInputStream()));
String cmdLine = "";
while ((cmdLine = buf.readLine()) != null) {
System.out.println(cmdLine);
}
} catch (Exception e) {
}
Related
As the title suggests I was wondering if there was a way to execute a maven command like this from Java code ...
mvn --dependency:get -Dartifact=groupid.com:artifactId:1.0.0-SNAPSHOT
I can run this from the command line but when I try to run this using the Java ProcessBuilder I get
Unable to parse command line options: Unrecognized option:
--dependency:get
It looks like the ProcessBuilder can't find the maven-dependency-plugin.
Here is my code snippet, note that the mvn --version command works but the command that requires the plugin does not :(
private static void RunCommand() {
//String command = "mvn --version";
String command = "mvn --dependency:get -Dartifact=groupid.com:artifactId:1.0.0-SNAPSHOT";
try {
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
if (isWindows) {
builder.command("cmd.exe", "/c", command);
} else {
builder.command("sh", "-c", command);
}
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
Is there anyway to tell ProcessBuilder where to find the maven plugin?
It should be
mvn dependency:get
reference
I'm trying to execute one sh file that run postgres commands, but it never ends.
The sh file is that:
#!/bin/bash
echo "My ARGUMENTS $1 $2 $3 $4";
psql -h $1 -p $2 -U $3 -d template1 -c "drop database IF EXISTS $4";
psql -h $1 -p $2 -U $3 -d template1 -c "create database $4";
echo "OPERATION COMPLETED";
And my java method is the following:
public void createDB() {
try{
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", "ls");
ProcessBuilder pb = new ProcessBuilder("/tmp/test.sh", "localhost", "5432", "postgres", "newDB");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}catch (Exception e) {
System.out.println("ERORR");
}
}
the output is:
My ARGUMENTS localhost 5432 postgres newDB
But never execute the second psql statement, can someone help me please.
The soluction was the following:
public void createDB() {
try{
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", "ls");
ProcessBuilder pb = new ProcessBuilder("/tmp/test.sh", "localhost", "5432", "postgres", "newDB");
// set environment variable password
env.put("PGPASSWORD", "123456");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}catch (Exception e) {
System.out.println("ERORR");
}
}
I pass the password by enviroment variable. Thanks to all!
I'm trying to run
docker-compose up -d
in Java application. Here's my code:
List<String> commands = new ArrayList<>();
commands.add("zsh");
commands.add("-c");
commands.add("docker-compose up --build");
Process dockerComposeCommand;
ProcessBuilder pb = new ProcessBuilder();
pb.command(commands);
pb.directory(new File(server_config.getDOCKERFILE_PATH()));
String path = System.getenv("PATH");
pb.environment().put("PATH","/usr/bin:"+path);
pb.redirectErrorStream(true);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
List<String> result = new ArrayList<>();
try {
dockerComposeCommand = pb.start();
dockerComposeCommand.waitFor();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(dockerComposeCommand.getInputStream()))) {
String line = reader.readLine();
while (line != null) {
result.add(line);
line = reader.readLine();
System.out.println(line);
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
However, the result was
zsh:1: command not found: docker-compose
I've checked my .zshrc file and add
export PATH="$PATH:/usr/local/bin"
to include docker-compose's path.
Did I miss something or docker-compose just can't simply execute by Java?
Any advice would be helpful!
I am trying to execute the following line in java(with escaped characters):
"psexec -i -d \\\\computerName -u user -p pass calc 2>
somePath\\psexecOut.txt"
I use the following method to execute cmd lines:
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
System.out.println("command is = \n"+command);
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
The line is executed and calc is starting , but the log part doesn't work. The log file psexecOut.txt is not created.
When I run the command normally (without excaped characters) in cmd it runs fine and the log file is created, but using java it doesn't create the log file.
I suspect that > needs to be escaped but as I read it's already escaped as it is.
How can I execute the psexec with log to text file in a single cmd line using java like I can do manually in windows console ?
Solved:
As lit suggested in the comments: cmd.exe /c works.
So the corrected method is:
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
System.out.println("command is = \n"+command);
Process p;
try {
p = Runtime.getRuntime().exec("cmd.exe /c "+command); // <-correction done here
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
Try putting cmd.exe /C at the beginning of the command? It is cmd.exe that interprets the > redirection.
"cmd.exe /C psexec -i -d \\\\computerName -u user -p pass calc 2> somePath\\psexecOut.txt"
I am writing a code to execute a command and reading the output
If I run the command on command prompt, it looks like this
Command is
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
Command produces multi line output. How can I print this output in my java code?
I have written following code, but it produces output as command itself that is
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
rather than actual command output as we can see it in the screenshot
final String cmd = "java -cp \"*\" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin";
final String path = "C:/Project/stanford-corenlp-full-2015-01-29/stanford-corenlp-full-2015-01-29";
String input = "excellent";
String cmdString = "echo '" +input + "' | " + cmd;
Process process = Runtime.getRuntime().exec(cmdString,null, new File(path));
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
Try using ProcessBuilder:
try {
ProcessBuilder pb = new ProcessBuilder("your command here");
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
while ((line = br.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
} catch (InterruptedException e) {
//handle exception
}