I would like to execute multiple commands in a cmd shell from java:
sample:
String cmdShell = "cmd /c start cmd.exe /K ";
String endCommand = cmdShell + "\"" + multiplecommands + " && exit" + "\"";
Process proc = Runtime.getRuntime().exec(endCommand);
final BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
LOGGER.debug("" + line);
}
proc.waitFor();
This opens the black window and closes after finished. Is there a way to hide this window. Or any other way to execute multiple commands without showing the cmd window ?
Maybe it useful "start" with "/min":
start /min .....
..........
exit
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/start
you can try this code , in my case this code give all Directory of C:\xampp folder in my console ...without open CMD
public static void main(String[] args)throws Exception {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "cd C:\\xampp && C: && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
for more study you can read this page
Related
I have a program called darknet. It's a C-program made from Darknet.
I want to run the darknet program in a folder Darknet that looks like this:
I'm going to run darknet with Java Process Builder, but I get no responce from it when I run this code:
// Arguments
String darknetNamePath = darknet.getValue().getFilePath().replace("Darknet/", "./");
String configurationFlag = configuration.getValue().getFilePath().replace("Darknet/", "");
String weightsFlag = weights.getValue().getFilePath().replace("Darknet/", "");
String imageFlag = "data/cameraSnap.png";
String thresholdFlag = "-thresh " + thresholds.getValue();
// Process builder
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.directory(new File("Darknet")); // We need to stand inside the folder "Darknet"
String commandString = "detect " + configurationFlag + " " + weightsFlag + " " + imageFlag + " " + thresholdFlag;
System.out.println("darknetNamePath = " + darknetNamePath);
System.out.println("commandString = " + commandString);
processBuilder.command(darknetNamePath, commandString);
Process process = processBuilder.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);
Here is my output. Why doesn't it work for me?
darknetNamePath = ./darknet
commandString = detect cfg/yolov2-tiny.cfg weights/yolov2-tiny.weights data/cameraSnap.png -thresh 0.8
Exited with error code : 0
But when I call darknet file via terminal, then it works.
./darknet detect cfg/yolov2-tiny.cfg weights/yolov2-tiny.weights data/cameraSnap.png -thresh 0.6
UPDATE 2:
Here is my update.
// Arguments
String darknetNamePath = darknet.getValue().getFile().getAbsolutePath();
String configurationFlag = configuration.getValue().getFilePath().replace("Darknet/", "");
String weightsFlag = weights.getValue().getFilePath().replace("Darknet/", "");
String imageFlag = "data/cameraSnap.png";
String thresholdFlag = "-thresh " + thresholds.getValue();
// Process builder
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(darknetNamePath, "detect", configurationFlag, weightsFlag, imageFlag, thresholdFlag);
Process process = processBuilder.start();
if (process.getInputStream().read() == -1) {
System.out.println(darknetNamePath);
System.out.println("detect");
System.out.println(configurationFlag);
System.out.println(weightsFlag);
System.out.println(imageFlag);
System.out.println(thresholdFlag);
System.out.printf("ERROR!");
}
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);
Output:
/home/dell/Dokument/GitHub/Vaadin-DL4J-YOLO-Camera-Mail-Reporter/Vaadin-DL4J-YOLO-Camera-Mail-Reporter/Darknet/darknet
detect
cfg/yolov2-tiny.cfg
weights/yolov2-tiny.weights
data/cameraSnap.png
-thresh 0.3
ERROR!
Exited with error code : 0
UPDATE 3:
This works:
// Arguments
String darkPath = darknet.getValue().getFilePath().replace("Darknet/", "./"); // We need to call ./darknet, not absolute path
String configurationFlag = configuration.getValue().getFilePath().replace("Darknet/", "");
String weightsFlag = weights.getValue().getFilePath().replace("Darknet/", "");
String imageFlag = "data/camera.png";
String thresValue = String.valueOf(thresholds.getValue());
// Process builder
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.directory(new File("Darknet")); // Important
processBuilder.command(darkPath, "detect", configurationFlag, weightsFlag, imageFlag, "-thresh", thresValue);
processBuilder.redirectErrorStream(true); // Important
Process process = processBuilder.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);
Your command must break all arguments into separate pieces - including thresholdFlag. It is a good idea to check if the executable exists. If it does not you should check where it is located or fix your Path variable to ensure that it can be located:
File darkpath = new File(darknetNamePath);
String [] cmd = new String[] { darkpath.getAbsolutePath(), "detect", configurationFlag, weightsFlag, imageFlag, "-thresh", String.valueOf(thresholds.getValue()) };
System.out.println("Path: "+darkpath+ " exists="+darkpath.exists());
System.out.println("exec "+Arrays.toString(cmd));
processBuilder.command(cmd);
It is also worth handling STDERR, the easiest way is to redirect STDERR=>STDOUT before calling processBuilder.start()
processBuilder.redirectErrorStream(true);
If you want Java to launch the executable without prefixing the absolute path it needs to be in one of these directories:
System.out.println("PATH COMPONENTS FOR JAVA LAUNCH:");
Arrays.asList(System.getenv("PATH").split(File.pathSeparator)).forEach(System.out::println);
You are using ProcessBuilder the wrong way. The command method takes a executable and arguments as separate strings, not a path and then another string with the actual command and all its arguments. There is no shell involved to do word splitting on the command, so you pass all your distinct arguments as one argument.
I don't have darknet, so here's a simple command using the Unix echo command:
import java.io.*;
public class ProcessBuilderTest {
public static void main(String[] args) throws Exception {
ProcessBuilder processBuilder = new ProcessBuilder();
String[] command = {"/bin/echo", "hello", "world"};
processBuilder.command(command);
Process process = processBuilder.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("Exited with error code : " + exitCode);
}
}
When I run this, I get:
robert#saaz:~$ java ProcessBuilderTest.java
hello world
Exited with error code : 0
It's not clear to my why your command doesn't produce an error. If I give a bad command (e.g., a trailing space behind "echo"), I get an exception:
Exception in thread "main" java.io.IOException: Cannot run program "/bin/echo ": error=2, No such file or directory
This may be OS specific. Or maybe you have some other darknet executable that gets picked up.
I am able to open some program, that can get instructions from cmd to do some stuff, like opening file with certain arguments, check if it's ready, etc...
That's how I open file through Java.
final String location = "C:\\Program";
final File dir = new File(location);
String cmd = "cmd.exe /c start my-program.exe";
Process process = Runtime.getRuntime().exec(cmd, null , dir);
How do I interact with it now, send commands like "check_status" or "do_some_stuff" and get it's output to Java.
If I try this:
String [] cmd = {"cmd.exe /c start my-program.exe", "do_stuff"};
Process process = Runtime.getRuntime().exec(cmd, null , dir);
I get error: "Cannot run program "cmd.exe /c start my-program.exe.exe" (in directory "C:\Program"): CreateProcess error=2, The system cannot find the file specified"
But it does finds file when I send single String as an argument.
I understand that I can get it's output to Java this way:
java.io.InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
EDIT: Solved by using getOutputStream.
Writer w = new OutputStreamWriter(process.getOutputStream());
w.write("custom_command");
w.close();
I started Wildfly server with standalone.bat file(similar .exe file)
public static void main(String[] args) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd D:\\Users\\turack\\Downloads\\wildfly-16.0.0.Final\\bin\\ && standalone.bat");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while (true) {
line = bufferedReader.readLine();
if (line == null) { break; }
System.out.println(line);
}
bufferedReader.close();
}
Solved by using getOutputStream.
Writer w = new OutputStreamWriter(process.getOutputStream());
w.write("custom_command");
w.close();
I am running my Java program from terminal and I am trying to count the number of files in a certain directory using a linux command in my code; I have managed to get output for all other commands but this one.
My command is: ls somePath/*.xml | wc -l
When I run my command in my code, it appears that it has nothing to output, yet when I run the same exact command in terminal it works just fine and actually outputs the number of xml files in that directory.
Here is my code:
private String executeTerminalCommand(String command) {
String s, lastOutput = "";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
System.out.println("Executing command: " + command);
while ((s = br.readLine()) != null){//it appears that it never enters this loop since I never see anything outputted
System.out.println(s);
lastOutput = s;
}
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
return lastOutput;//returns empty string ""
}
Updated code w/ output
private String executeTerminalCommand(String command) {
String s, lastOutput = "";
try {
Process p = new ProcessBuilder().command("/bin/bash", "-c", command).inheritIO().start();
//Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
System.out.println("Executing command: " + command);
while ((s = br.readLine()) != null){
System.out.println("OUTPUT: " + s);
lastOutput = s;
}
System.out.println("Done with command------------------------");
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("LAST OUTPUT IS: " + lastOutput);
return lastOutput;
}
output:
Executing command: find my/path -empty -type f | wc -l
Done with command------------------------
1
LAST OUTPUT IS:
To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.
Process p = new ProcessBuilder().command("bash", "-c", command).start();
bash invokes a shell to execute your command and -c means commands are read from string. So, you don't have to send the command as an array in ProcessBuilder.
But if you want to use Runtime then
String[] cmd = {"bash" , "-c" , command};
Process p = Runtime.getRuntime().exec(cmd);
Note: You can check advantages of ProcessBuilder here and features here over Runtime
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
}
The uploaded Screenshot conatains the start_client.bat file content, viewed in notepad++ editor.
Currently am invoking start_client.bat on local machine it works fine but when the same bat file is invoked on server it pops up a window on server and it needs manual closure after execution. Any way to force bat file execution on server without window poppping up.
private void invokeSeagull(String flag) throws Exception
{
String path="";
if(flag.equals("Start"))
{
path="cmd /c start D:/Seagull/TIB/start_client.bat";
}
if(flag.equals("Stop"))
{
path="cmd /c start D:/Seagull/TIB/stop_client.bat";
}
try {
String line;
Process p = Runtime.getRuntime().exec(path);
p.waitFor();
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
}
catch (Exception err) {
err.printStackTrace();
}
}
This code snippet should run batch file, of course if you use Windows.
Runtime.getRuntime().exec("cmd /c start {pathToFile}");
As pointed out be ssedano the correct way to execute shell commands in Java is the Process-builder:
// Just the name of an executable is enough
final ProcessBuilder pb = new ProcessBuilder( "test.bat" );
pb.redirectError( Redirect.INHERIT );
pb.redirectOutput( Redirect.INHERIT );
System.out.println( String.format( "***** Running Process %s OUTPUT:", pb.command().toString() ) );
final Process process = pb.start();
process.getOutputStream().close();
final int returnCode = process.waitFor();
System.out.println( "***** Process Exited with Returncode: " + returnCode );
You can just redirect STDERR and STDOUT of the bat-file, so you will get all output in the Server-Output console. And you should close STDIN of the bat-file, so it will exit and not get stuck on the pause command at the end!
You could use the new in Java 7 ProcessBuilder
A simple example:
String[] command = {"CMD", "/C", "dir"};
ProcessBuilder probuilder = new ProcessBuilder(command);
// Set up your work directory
probuilder.directory(new File("c:\\stackoverflow"));
Process process = probuilder.start();
// Read output
try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);)
{
String line;
System.out.printf("Output of running %s is:\n", Arrays.toString(command));
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
// Wait to get exit value
int exitValue = process.waitFor();
}
catch (Exception e)
{
// Fail
}
This should run in the silent mode :
Runtime.getRuntime().exec(new String[] {"cmd", "/pathto/start_client.bat"});