Run windows commands from java

Run windows commands from java

If you want to run DOS or Windows commands from a Java program it can be done using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).

Java RunTime class

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

In RunTime class there is a exec() method that executes the specified string command in a separate process. Using this exec() method dos or windows commands can be executed from Java.

Runtime.getRunTime().exec to run dos/windows commands in Java example

Here it can be seen that directory listing is displayed for the directory which happens to be the workspace directory from where I executed the Java program.

Runtime.getRuntime().exec method is used to run the command.

  • public static Runtime getRuntime() — Returns the runtime object associated with the current Java application.
  • public Process exec(String command) throws IOException — Executes the specified string command in a separate process.

cmd /c which is used with the command has the following explanantion —

  • cmd— Starts a new command shell
  • /c— Executes the given command and terminates

Execution of the command returns instance of class Process. Using the getInputStream() method of Process class output of the executed command can be printed by reading the stream.

Running command Using ProcessBuilder

You can also use ProcessBuilder class to run dos or windows command from Java. If you have to run the same command as used above using ProcessBuilder, which is a much clearer way to do that, you can create a list with the command and the required arguments and then pass it to ProcessBuilder instance as command.

Recommendations for learning

That’s all for this topic Running Dos/Windows Commands From Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

How do I run a Java program from the command line on Windows?

I’m trying to execute a Java program from the command line in Windows. Here is my code:

I’m not sure how to execute the program — any help? Is this possible on Windows? Why is it different than another environment (I thought JVM was write once, run anywhere)?

12 Answers 12

Let’s say your file is in C:\mywork\

Run Command Prompt

This makes C:\mywork the current directory.

This displays the directory contents. You should see filenamehere.java among the files.

This tells the system where to find JDK programs.

This runs javac.exe, the compiler. You should see nothing but the next system prompt.

javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.

Читайте также:  Журнал регистрации пользователей windows

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!

To complete the answer :

Compile the Java File to a *.class file

  • This will create a TheJavaFile.class file

Execution of the Java File

Creation of an executable *.jar file

You’ve got two options here —

With an external manifest file :

Create the manifest file say — MANIFEST.mf

The MANIFEST file is nothing but an explicit entry of the Main Class

jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class

Executable by Entry Point:

To run the Jar File

In case your Java class is in some package. Suppose your Java class named ABC.java is present in com.hello.programs , then you need to run it with the package name.

Compile it in the usual way:

But to run it, you need to give the package name and then your java class name:

Complile a Java file to generate a class:

Execute the generated class:

Assuming the file is called «CopyFile.java», do the following:

The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).

Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.

This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330

For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html

It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.

Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.

Then you can compile your file using command

Then run it using

So that is how you compile and run a java program in cmd. You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.

You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they’re in the same directory

If you’re having an issue resulting with «could not find or load main class» you may not have jre in your path. Have a look at this question: Could not find or load main class

On Windows 7 I had to do the following:

quick way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads
  2. in windows, browse into «C:\Program Files\Java\jdk1.8.0_91\bin» (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do «open command window here» and this will give you a command line and access to all the BIN tools. «javac» is not by default in the windows system PATH environment variable.
  3. Follow comments above about how to compile the file («javac MyFile.java» then «java MyFile») https://stackoverflow.com/a/33149828/194872
Читайте также:  Dameware microsoft windows network

long way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but «javac» is NOT one of them so when trying to run «javac» from Windows command line it throws an error.
  3. I edited the path: Control Panel -> System -> Advanced tab -> «Environment Variables. » button -> scroll down to «Path», highlight and edit -> replaced the «C:\ProgramData\Oracle\Java\javapath» with a direct path to the java BIN folder «C:\Program Files\Java\jdk1.8.0_91\bin».

This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.

How to run Windows command from Java

I would like execute the following command with Java:

«C:\Program Files\MySQL\MySQL Server 5.5\bin\»mysqldump -u root —password=xxxx —routines database > C:\Users\john\Desktop\backup.sql

The command works perfectly when I use the Windows cmd.exe but not with my Java application.

I got the following error:

«C:\Program Files\MySQL\MySQL Server 5.5\bin\»mysqldump -u root —password=xxxx —routines database > C:\Users\john\Desktop\backup.sql java.io.IOException: Cannot run program «»C:\Program»: CreateProcess error=5, Access is denied

Do you have any idea?

2 Answers 2

Error 5 is either 1) cannot access the file/folder or 2) don’t have permissions.

Looks like the space in your ‘Program File’ directory name may be causing trouble causing trouble. Check where it says «Cannot run program «»C:\Program». This is obviously not a reference to the command you are trying to run. What I would do is add MySQL to your path and then just call the mysqldump command without the path to it. If you don’t want to do this, you can define a system variable and reference it with %MYSQL_HOME%\mysqldump.

Once you have the path resolved, if this still doesn’t work, you’ll want to look at the permissions for the command. You’ll need to make sure that the process has permission to execute the command. I think this in local admin groups or something like that.

How can I run multiple commands in just one cmd windows in Java?

what I would like to do is run a batch file multiple times from a java application. Therefore I set up a for-loop that runs this code n times:

The problem is that now each time the command is run a new cmd window pops up. However, what I want is just one window that pops up at the beginning and that is used to display all data from the following command calls.

How can I do that?

4 Answers 4

With && you can execute more than one commands, one after another:

Using multiple commands and conditional processing symbols

You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol.

For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful. You can use the special characters listed in the following table to pass multiple commands.

& [. ] command1 & command2
Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.

&& [. ] command1 && command2
Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.

|| [. ] command1 || command2
Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).

( ) [. ] (command1 & command2)
Use to group or nest multiple commands.

; or , command1 parameter1;parameter2
Use to separate command parameters.

Running windows 10 ubuntu bash commands from java [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 4 years ago .

T’m using windows 10, apparently the only way for me to run UNIX commands is to download ubuntu bash for windows 10.

I’m writing a java application using swing, which will run a set of UNIX commands upon clicking on the button, but I was thinking is it possible to run this commands with ubuntu bash for windows 10 ?

2 Answers 2

You assume that

the only way for me to run UNIX commands is to download ubuntu bash for windows 10

, but it’s not correct.

A rough search with the keyword «run linux command in windows» leads us to various solutions, above all, two, as stated here:

  1. Run Bash Shell from Windows 10
  2. Install Cygwin.

Actually, I have a third way: install Github for Windows to enable Bash in Windows. As stated here. This approach may be more limited to Cygwin, I haven’t test it.

I have installed both Cygwin x64 and Github without conflict, so you can just use them in cmd console. I think your question may change into «How can I run Bash command in Java in Windows if the Bash is enabled?»

Now, I don’t know if you have been aware of how to run Bash commands from Java. If so, you are done here. If not, ask Google.

A little more search before asking here is always helpful. Google is smarter than we think, and most of the time, even smarter than most of us, may we admit it or not.

Читайте также:  Звуки для запуска windows привет
Оцените статью