I am trying to run this command from java code and expecting a file to be generated with 1 liner code :
cut -d , -f 2 /online/data/test/output/2Zip/brita_ids-*.csv | sort -u | tr -d '\n' | sha512sum > /online/data/test/output/file_name.txt
This cmd is fine when I am running from cmd line but something wrong with my java code that I gatting hard time to figure out and I am not seeing the expected file being generated. Any clue whay may have happened here?
Here is my code to generate that file :
public String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
LOG.info( "Executing cmd : " + command );
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();
LOG.error( "Error in executing cmd : " + command + " \nError : " + e.getMessage() );
}
return output.toString();
}
Thanks in advance.
As RealSkeptic pointed out, pipe characters (|) are not command arguments; they're interpreted by a shell. And you are calling a command (cut) directly rather than using a shell.
This isn't a direct answer to your question, but you can accomplish your task without any shell commands:
Charset charset = Charset.defaultCharset();
MessageDigest digest = MessageDigest.getInstance("SHA-512");
try (DirectoryStream<Path> dir = Files.newDirectoryStream(
Paths.get("/online/data/test/output/2Zip"), "brita_ids-*.csv")) {
for (Path file : dir) {
Files.lines(file, charset)
.map(line -> line.split(",")[1])
.sorted(Collator.getInstance()).distinct()
.forEach(value -> digest.update(value.getBytes(charset)));
}
}
byte[] sum = digest.digest();
String outputFile = "/online/data/test/output/file_name.txt";
try (Formatter outputFormatter = new Formatter(outputFile)) {
for (byte sumByte : sum) {
outputFormatter.format("%02x", sumByte);
}
outputFormatter.format(" *%s%n", outputFile);
}
Thank you all, specifically #RealSkeptic and #qingl97. With your suggestion, I made a small change and that worked.
Process p = Runtime.getRuntime().exec(
new String[]{"sh","-c",command});
p.waitFor()
Try this if you want to get the output as well. ProcessBuilder would be better for multiple arguments and commans
try {
Process process = Runtime
.getRuntime()
.exec("cut -d , -f 2 /online/data/test/output/2Zip/brita_ids-*.csv | sort -u | tr -d '\n' | sha512sum > /online/data/test/output/file_name.txt");
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = reader.readLine();
while (line != null) {
// print the output to Console
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("Finished");
Something like this if you want a series of commands
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && 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);
}
From SOQuestion
Related
I found several code snippets for running cmd commands through a Java class, but I wasn't able to understand it.
This is code for opening the cmd
public void excCommand(String new_dir){
Runtime rt = Runtime.getRuntime();
try {
rt.exec(new String[]{"cmd.exe","/c","start"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I found some other links for adding other commands such as cd
http://www.coderanch.com/t/109753/Linux-UNIX/exec-command-cd-command-java
How to open the command prompt and insert commands using Java?
Can anyone help me to understand how to cd a directory such as:
cd C:\Program Files\Flowella
then run other commands on that directory?
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.
The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && 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);
}
}
}
Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
You can try this:-
Process p = Runtime.getRuntime().exec(command);
If you want to perform actions like cd, then use:
String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));
Example:
String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();
It is important that you split the command and all arguments in separate strings of the string array (otherwise they will not be provided correctly by the ProcessBuilder API).
Here is a more complete implementation of command line execution.
Usage
executeCommand("ls");
Output:
12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src
Code
private void executeCommand(String command) {
try {
log(command);
Process process = Runtime.getRuntime().exec(command);
logOutput(process.getInputStream(), "");
logOutput(process.getErrorStream(), "Error: ");
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void logOutput(InputStream inputStream, String prefix) {
new Thread(() -> {
Scanner scanner = new Scanner(inputStream, "UTF-8");
while (scanner.hasNextLine()) {
synchronized (this) {
log(prefix + scanner.nextLine());
}
}
scanner.close();
}).start();
}
private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");
private synchronized void log(String message) {
System.out.println(format.format(new Date()) + ": " + message);
}
My example (from real project)
folder — File.
zipFile, filesString — String;
final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
logger.info("Start unzipping: {} into the folder {}", command, folder.getPath());
final Runtime r = Runtime.getRuntime();
final Process p = r.exec(command, null, folder);
final int returnCode = p.waitFor();
if (logger.isWarnEnabled()) {
final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
logger.warn(line);
}
final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = is2.readLine()) != null) {
logger.warn(line);
}
}
The easiest way would be to use Runtime.getRuntime.exec().
For example, to get a registry value for the default browser on Windows:
String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
e.printStackTrace();
}
Then use a Scanner to get the output of the command, if necessary.
Scanner kb = new Scanner(process.getInputStream());
Note: the \ is an escape character in a String, and must be escaped to work properly (hence the \\).
However, there is no executable called cd, because it can't be implemented in a separate process.
The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly.
Easiest way for your command:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
Try this:
Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
Once you get the reference to Process, you can call getOutpuStream on it to get the standard input of the cmd prompt. Then you can send any command over the stream using write method as with any other stream.
Note that it is process.getOutputStream() which is connected to the stdin on the spawned process. Similarly, to get the output of any command, you will need to call getInputStream and then read over this as any other input stream.
Stopping and Disabling a service can be done via below code:
static void sdService() {
String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
try {
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
p.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Enabling and Starting a service can be done via below code
static void esService() {
String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
try {
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
//Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Executing command from any folder can be done via below code.
static void runFromSpecificFolder() {
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
//processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
processBuilder.redirectErrorStream(true);
Process p = processBuilder.start();
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
sdService();
runFromSpecificFolder();
esService();
}
You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.
To set the current working directory in your actual Java program, you should write:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
public class Demo {
public static void main(String args[]) throws IOException {
Process process = Runtime.getRuntime().exec("/Users/******/Library/Android/sdk/platform-tools/adb" + " shell dumpsys battery ");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while (true) {
line = in.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
The simplest and shortest way is to use CmdTool library.
new Cmd()
.configuring(new WorkDir("C:/Program Files/Flowella"))
.command("cmd.exe", "/c", "start")
.execute();
You can find more examples here.
one of the way to execute cmd from java !
public void executeCmd() {
String anyCommand="your command";
try {
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);
} catch (IOException e) {
e.printStackTrace();
}
}
Here the value adder is use of ampersands to batch commands and correct format for change drive with cd.
public class CmdCommander {
public static void main(String[] args) throws Exception {
//easyway to start native windows command prompt from Intellij
/*
Rules are:
1.baseStart must be dual start
2.first command must not have &.
3.subsequent commands must be prepended with &
4.drive change needs extra &
5.use quotes at start and end of command batch
*/
String startQuote = "\"";
String endQuote = "\"";
//String baseStart_not_taking_commands = " cmd /K start ";
String baseStart = " cmd /K start cmd /K ";//dual start is must
String first_command_chcp = " chcp 1251 ";
String dirList = " &dir ";//& in front of commands after first command means enter
//change drive....to yours
String changeDir = " &cd &I: ";//extra & makes changing drive happen
String javaLaunch = " &java ";//just another command
String javaClass = " Encodes ";//parameter for java needs no &
String javaCommand = javaLaunch + javaClass;
//build batch command
String totalCommand =
baseStart +
startQuote +
first_command_chcp +
//javaCommand +
changeDir +
dirList +
endQuote;
System.out.println(totalCommand);//prints into Intellij terminal
runCmd(totalCommand);
//Thread t = Thread.currentThread();
//t.sleep(3000);
System.out.println("loppu hep");//prints into Intellij terminal
}
public static void runCmd(String command) throws Exception {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
}
}
I am executing grep command from java on a linux file. Its always returning null for the following code.
Process p;
String matchStr="testmatch";
String output = null;
try {
String command = "grep \""+matchStr+"\" "+ filename;
System.out.println("Running command: " + command);
p = Runtime.getRuntime().exec(command);
System.out.println("***********************************");
System.out.println("***********************************");
System.out.println("***********************************");
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (br.readLine() != null) {
System.out.println("in while loop");
System.out.println("in while loop");
System.out.println("in while loop");
System.out.println(output);
System.out.println("***********************************");
System.out.println("***********************************");
System.out.println("***********************************");
System.out.println("***********************************");
// Process your output here
}
System.out.println("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
If i grep it directly it shows output but from java it never gets into while loop.
Please suggest whats wrong here.
The problem is that you do not write anything to output so it stays null. I guess you have to rewrite your while loop like this
while ((output = br.readLine()) != null) {
// Process your output here
}
Take a note that this syntax is discouraged by most style check due to it's abmiguity
Also it's a good idea to place p.waitFor() after while loop so grep would not hang on flushig std(err|out).
UPDATE
Also it is a good idea to use ProcessBuilder (available since java-7) instead of Runtime.getRuntime().exec(...) because you will have more control over the process i.e
final ProcessBuilder builder = new ProcessBuilder();
builder.command("grep", matchStr, filename);
// redirect stderr to stdout
builder.redirectErrorStream(true);
final Process process = builder.start();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String output = null;
while ((output = br.readLine()) != null) {
System.out.println(output);
// Process your output here
}
process.waitFor();
After turning your code into a https://stackoverflow.com/help/mcve it works for me.
Here the file does not exist:
robert#habanero:~$ rm /home/robert/greptest.txt
robert#habanero:~$ javac GrepTest.java && java GrepTest
Running command: grep test /home/robert/greptest.txt
exit: 2
Now the file does exist but does not contain the text to be found:
robert#habanero:~$ echo not found > /home/robert/greptest.txt
robert#habanero:~$ javac GrepTest.java && java GrepTest
Running command: grep test /home/robert/greptest.txt
exit: 1
Now the file exists and contains the text:
robert#habanero:~$ echo test this > /home/robert/greptest.txt
robert#habanero:~$ javac GrepTest.java && java GrepTest
Running command: grep test /home/robert/greptest.txt
test this
exit: 0
Here is the code:
import java.io.*;
public class GrepTest {
public static void main(String[] args) throws Exception {
String command = "grep test /home/robert/greptest.txt";
System.out.println("Running command: " + command);
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
System.out.println("exit: " + p.exitValue());
p.destroy();
}
}
I was recently struggling with a similar issue, and I believe I the solution I found is an answer also to your problem (though your question is a bit malformed as others have pointed out).
The issue pertrains to the quote marks around your search string,
\""+matchStr+"\"
The java exec command will literally deliver these to the grep command, and instead of searching for matchStr, grep will be looking for "matchStr", and the results will not be what you are expecting.
This applies also in case one is executing the command as an array like
final Process process = Runtime.getRuntime().exec(new String[] { "grep", "-C1000", searchString, fileName } );
Pass the plain searchString without including quotation marks into the string.
I have this bash:
#!/bin/bash
# File to be tagged
inputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/Text.txt"
#inputfile="test/SampleInputs/longParagraph.txt"
# Tagged file to be created
#outputfile="test/SampleOutputs/NERTest.conll.tagged.txt"
outputfile="/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/SinaGolestanirad-Project/1.Generate-Basic-Questions/Tagged-Named-Entites-Text.txt"
# Config file
#configfile="config/conll.config"
configfile="config/ontonotes.config"
# Classpath
cpath="target/classes:target/dependency/*"
CMD="java -classpath ${cpath} -Xmx8g edu.illinois.cs.cogcomp.LbjNer.LbjTagger.NerTagger -annotate ${inputfile} ${outputfile} ${configfile}"
echo "$0: running command '$CMD'..."
$CMD
When I run either java codes below they do not give any errors but they just show the bash file in my Eclipse Console, in other words they do not run the bash !! and the value for process.exitValue() is 1, by the way, my OS is CentOS, linux.
Firs JAVA code :
try {
Process process = new ProcessBuilder(command).start();
process.waitFor();
System.out.println(process.exitValue());
BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.out.println("exec response: " + line);
}
} catch (Exception e) {
System.out.println(e);
}
Second JAVA code :
String command = "/dfs/sina/SinaGolestanirad-Project-OneTextEachTime/"
+ "SinaGolestanirad-Project/1.Generate-Basic-Questions/1.IllinoisNerExtended-DO-NOT-OPEN-BY-ECLIPSE/plaintextannotate-linux.sh";
StringBuffer output = new StringBuffer();
Process p;
try {
String[] cmd = new String[]{"/bin/bash",command};
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output.toString());
} catch (Exception e) {
e.printStackTrace();
}
I also checked the bash file permission and it is executable as a program.
How can I run the bash file? The bash should run another program written in java.
-- LeBarton what is the exit code?
Check the output of p.exitValue()
p.waitFor()
InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream());
While (inputStreamReader.ready()) { System.out.println(inputStreamReader.read(); }
This will show you the error output. Add this to the bottom below the try.. catch.
You will see the output that you would see on the command line. It will help you narrow down the error.
I found a link which may help, if your bash read some environmental variables.
$PATH variable isn't inherited through getRuntime().exec
I am using Runtime.getRuntime().exec() to execute a command through Java, but I am having problem regarding path (with spaces) to run the command.
I have enclose the path with " (double-quotes) and also tried with ' (single-quotes), but failed...:(:(:(
My code is :
private void encryptFile(String csvFilePath) throws IOException {
Process proc = Runtime.getRuntime().exec("gpg --recipient testKey2014 --output '" + csvFilePath + ".gpg' --encrypt '" + csvFilePath + "'");
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
if (stdInput.ready()) {
// 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);
}
}
if (stdError.ready()) {
// 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);
}
}
}
I've also tried same String in my terminal and it is executing fine, but here since the csvFilePath containing (space), that's why the command is not working.
The actual command is :
gpg --recipient testKey2014 --output '/home/avis/testDir/File Transfers/Recordings/PH2014050401/PH2014050401.zip.gpg' --encrypt '/home/avis/testDir/File Transfers/Recordings/PH2014050401/PH2014050401.zip'
OUTPUT is :
Here is the standard error of the command (if any):
usage: gpg [options] [filename]
Anyone suggest what to do???
Just use the array version of exec:
Process proc = Runtime.getRuntime().exec(new String[]{"gpg",
"--recipient",
"testKey2014",
"--output",
csvFilePath + ".gpg",
"--encrypt"
csvFilePath});
I found several code snippets for running cmd commands through a Java class, but I wasn't able to understand it.
This is code for opening the cmd
public void excCommand(String new_dir){
Runtime rt = Runtime.getRuntime();
try {
rt.exec(new String[]{"cmd.exe","/c","start"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I found some other links for adding other commands such as cd
http://www.coderanch.com/t/109753/Linux-UNIX/exec-command-cd-command-java
How to open the command prompt and insert commands using Java?
Can anyone help me to understand how to cd a directory such as:
cd C:\Program Files\Flowella
then run other commands on that directory?
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.
The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && 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);
}
}
}
Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
You can try this:-
Process p = Runtime.getRuntime().exec(command);
If you want to perform actions like cd, then use:
String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));
Example:
String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();
It is important that you split the command and all arguments in separate strings of the string array (otherwise they will not be provided correctly by the ProcessBuilder API).
Here is a more complete implementation of command line execution.
Usage
executeCommand("ls");
Output:
12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src
Code
private void executeCommand(String command) {
try {
log(command);
Process process = Runtime.getRuntime().exec(command);
logOutput(process.getInputStream(), "");
logOutput(process.getErrorStream(), "Error: ");
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void logOutput(InputStream inputStream, String prefix) {
new Thread(() -> {
Scanner scanner = new Scanner(inputStream, "UTF-8");
while (scanner.hasNextLine()) {
synchronized (this) {
log(prefix + scanner.nextLine());
}
}
scanner.close();
}).start();
}
private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");
private synchronized void log(String message) {
System.out.println(format.format(new Date()) + ": " + message);
}
My example (from real project)
folder — File.
zipFile, filesString — String;
final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
logger.info("Start unzipping: {} into the folder {}", command, folder.getPath());
final Runtime r = Runtime.getRuntime();
final Process p = r.exec(command, null, folder);
final int returnCode = p.waitFor();
if (logger.isWarnEnabled()) {
final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
logger.warn(line);
}
final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = is2.readLine()) != null) {
logger.warn(line);
}
}
The easiest way would be to use Runtime.getRuntime.exec().
For example, to get a registry value for the default browser on Windows:
String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
e.printStackTrace();
}
Then use a Scanner to get the output of the command, if necessary.
Scanner kb = new Scanner(process.getInputStream());
Note: the \ is an escape character in a String, and must be escaped to work properly (hence the \\).
However, there is no executable called cd, because it can't be implemented in a separate process.
The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly.
Easiest way for your command:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
Try this:
Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
Once you get the reference to Process, you can call getOutpuStream on it to get the standard input of the cmd prompt. Then you can send any command over the stream using write method as with any other stream.
Note that it is process.getOutputStream() which is connected to the stdin on the spawned process. Similarly, to get the output of any command, you will need to call getInputStream and then read over this as any other input stream.
Stopping and Disabling a service can be done via below code:
static void sdService() {
String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
try {
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
p.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Enabling and Starting a service can be done via below code
static void esService() {
String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
try {
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
//Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Executing command from any folder can be done via below code.
static void runFromSpecificFolder() {
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
//processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
processBuilder.redirectErrorStream(true);
Process p = processBuilder.start();
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
sdService();
runFromSpecificFolder();
esService();
}
You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.
To set the current working directory in your actual Java program, you should write:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
public class Demo {
public static void main(String args[]) throws IOException {
Process process = Runtime.getRuntime().exec("/Users/******/Library/Android/sdk/platform-tools/adb" + " shell dumpsys battery ");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while (true) {
line = in.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
The simplest and shortest way is to use CmdTool library.
new Cmd()
.configuring(new WorkDir("C:/Program Files/Flowella"))
.command("cmd.exe", "/c", "start")
.execute();
You can find more examples here.
one of the way to execute cmd from java !
public void executeCmd() {
String anyCommand="your command";
try {
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);
} catch (IOException e) {
e.printStackTrace();
}
}
Here the value adder is use of ampersands to batch commands and correct format for change drive with cd.
public class CmdCommander {
public static void main(String[] args) throws Exception {
//easyway to start native windows command prompt from Intellij
/*
Rules are:
1.baseStart must be dual start
2.first command must not have &.
3.subsequent commands must be prepended with &
4.drive change needs extra &
5.use quotes at start and end of command batch
*/
String startQuote = "\"";
String endQuote = "\"";
//String baseStart_not_taking_commands = " cmd /K start ";
String baseStart = " cmd /K start cmd /K ";//dual start is must
String first_command_chcp = " chcp 1251 ";
String dirList = " &dir ";//& in front of commands after first command means enter
//change drive....to yours
String changeDir = " &cd &I: ";//extra & makes changing drive happen
String javaLaunch = " &java ";//just another command
String javaClass = " Encodes ";//parameter for java needs no &
String javaCommand = javaLaunch + javaClass;
//build batch command
String totalCommand =
baseStart +
startQuote +
first_command_chcp +
//javaCommand +
changeDir +
dirList +
endQuote;
System.out.println(totalCommand);//prints into Intellij terminal
runCmd(totalCommand);
//Thread t = Thread.currentThread();
//t.sleep(3000);
System.out.println("loppu hep");//prints into Intellij terminal
}
public static void runCmd(String command) throws Exception {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
}
}