Running Command Line in Java
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
Run cmd commands through Java
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
How do I run a Java program from the command line on Windows?
Source: javaindos.
Let's say your file is in C:\mywork\
Run Command Prompt
C:\> cd \mywork
This makes C:\mywork the current directory.
C:\mywork> dir
This displays the directory contents. You should see
filenamehere.java among the files.C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin
This tells the system where to find JDK programs.
C:\mywork> javac filenamehere.java
This runs javac.exe, the compiler. You should see nothing but the
next system prompt...C:\mywork> dir
javac has created the filenamehere.class file. You should see
filenamehere.java and filenamehere.class among the files.C:\mywork> java filenamehere
This runs the Java interpreter. You should then see your program
output.If the system cannot find javac, check the set path command. If javac
runs but you get errors, check your Java text. If the program
compiles but you get an exception, check the spelling and
capitalization in the file name and the class name and the java
HelloWorld command. Java is case-sensitive!
Running a command-line operation from within Java
The "move" command is part of the cmd.exe interpreter, and not a executable by itself.
This would work:
cmd.exe /c move file1 file2
How to execute cmd commands through java
You can try below code
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K java -jar selenium-server-standalone-2.44.0.jar -role hub");
However this will run executable jar from your current directory, where you .class file exist.
how can I execute java command by java code?
Your problem may be a difference between PATH of the current running VM, compared the shell (bash etc) you use and implicit passing of CLASSPATH. Check the location of java which which java
in the shell that works and try using in your exec
.
Also you won't see all issues when running as you don't access the error stream at same time as the output stream, changing to ProcessBuilder allows easier debugging as you can redirect the out/err streams to a file. But if JADE runs for a long time or produces a lot of output you should consumer STDOUT+ERR in background threads.
Try this in jshell:
String[] cmd = new String[]{"java", "jade.Boot", "-gui"};
ProcessBuilder pb = new ProcessBuilder(cmd);
File fileOut = new File("stdout.log");
File fileErr = new File("stderr.log");
pb.redirectError(fileErr);
pb.redirectOutput(fileOut);
Process p = pb.start();
int rc = p.waitFor();
String stdout = Files.readString(fileOut.toPath());
String stderr = Files.readString(fileErr.toPath());
System.out.println("Exit : "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****"));
System.out.println("STDOUT : "+stdout);
System.out.println("STDERR : "+stderr);
How to open the command prompt and insert commands using Java?
I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.
rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");
How do I run command line from Java code in the background?
Removing the 'start' completely will do what you want (as this is what is creating the window):
Process process = Runtime.getRuntime().exec("cmd /c rake.bat");
I have tested this and it works, ofcourse if you want to communicate with the command prompt you'd have to have Input and Output streams, also not forgetting your Error stream
As stated in the comment though removing 'start' on XP wont help (as it wont work).
Running Java module from command line breaks when I reverse argument order
Official documentation:
To launch the main class in a module:
java [options] -m module[/mainclass] [args...]
-p
is an option that must come before -m
Related Topics
Why Do We Usually Use || Over |? What Is the Difference
How to Solve Javax.Net.Ssl.Sslhandshakeexception Error
How to Read a Specific Line Using the Specific Line Number from a File in Java
Using Graphics2D to Overlay Text on a Bufferedimage and Return a Bufferedimage
Comparator.Reversed() Does Not Compile Using Lambda
How to Print a Float with 2 Decimal Places in Java
What Is This: [Ljava.Lang.Object;
Is a Java Hashmap Search Really O(1)
Java Resultset How to Check If There Are Any Results
Java String Replace Not Working
Why Is Creating a Thread Said to Be Expensive
Java: Define Terms Initialization, Declaration and Assignment
Why Are Filenames in Java the Same as the Public Class Name
Why Doesn't Java Send the Client Certificate During Ssl Handshake
Java.Lang.Unsupportedclassversionerror: Bad Version Number in .Class File