Execute Java Program In Cmd

Posted on
Active4 months ago
  1. Compiling Java Program In Command Prompt
  2. Update Java In Cmd
  3. Java Program Tutorials
  4. How To Execute Java Program In Cmd

Java and the Windows Command Prompt This page is obsolete. This document instructs you on how to use the Windows Command Prompt with Java. These instructions are specialized to Windows 7, but are similar for Windows XP and Windows Vista.

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)?

Bob Jarvis

Hello World in Java on Windows (manual instructions) This document instructs you on how to manually setup a Java programming environment for your Windows computer and provides a step-by-step guide for creating, compiling, and executing a Java program using either DrJava or the Command Prompt. How to run command-line or execute external application from Java. For instance, you are developing a Java application and need to execute external application (another executable program) in the middle of the program or you may need to execute some commands such as listing directory command: dir (in windows) or ls. Being spoiled by IDEs and automated building tools I recently realized that I don't know how to run java code from a command line anymore. After playing a guessing game for an hour trying to compile a simple piece of code that took 5 minutes to write, I thought maybe it's time to do a little research. How To Run Java Program In Command Prompt (cmd) Java programs are run using the command java In this example, the class name is HelloWorld, type java HelloWorld and press Enter; The Java Virtual Machine (JVM) looks for a file matching the class name with the extension.class; The JVM executes the program and displays the output “Hello! This following example demonstrates how you can execute a command line program in Windows from your Java program. This program will also print the results of the command. Note that in this case we are using another version of the Runtime.exec method. This program runs 'ipconfig' command with /all command line argument.

37.7k6 gold badges63 silver badges93 bronze badges
Elizabeth TurnerElizabeth Turner
1,1013 gold badges10 silver badges11 bronze badges

12 Answers

Mapinfo free trial. Source: javaindos.

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.

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!

Liam
17.3k16 gold badges80 silver badges135 bronze badges
Nicholas KadaeuxNicholas Kadaeux
2,3262 gold badges10 silver badges11 bronze badges

To complete the answer :

  1. The Java File

  2. Compile the Java File to a *.class file

    • This will create a TheJavaFile.class file
  3. Execution of the Java File

  4. Creation of an executable *.jar file

    • You've got two options here -

      1. 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

      2. Executable by Entry Point:

        • jar -cvfe TheJavaFile.jar <MainClass> TheJavaFile.class
  5. To run the Jar File

Jiri Tousek
11.2k5 gold badges24 silver badges40 bronze badges
jkhoslajkhosla
1,4671 gold badge9 silver badges12 bronze badges

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:

Dawid Ferenczy Rogožan
13.1k8 gold badges52 silver badges55 bronze badges
Harshad HolkarHarshad Holkar

Complile a Java file to generate a class:

Execute the generated class:

Dawid Ferenczy Rogožan
13.1k8 gold badges52 silver badges55 bronze badges
Paresh3489227Paresh3489227

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

javac A.java

Then run it using

java A

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.

Compiling Java Program In Command Prompt

Eliza HelenaEliza Helena

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 havejre in your path. Have a look at this question:Could not find or load main class

Community
monikamonika
3651 gold badge5 silver badges17 bronze badges

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).

YakovKYakovK

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 FilesJavajdk1.8.0_91bin' (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

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:ProgramDataOracleJavajavapath. 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:ProgramDataOracleJavajavapath' with a direct path to the java BIN folder 'C:Program FilesJavajdk1.8.0_91bin'.
  4. This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.

  5. Follow comments above about how to compile the file ('javac MyFile.java' then 'java MyFile') https://stackoverflow.com/a/33149828/194872

Community
Chris SmithChris Smith

STEP 1: FIRST OPEN THE COMMAND PROMPT WHERE YOUR FILE IS LOCATED. (right click while pressing shift)
STEP 2: THEN USE THE FOLLOWING COMMANDS TO EXECUTE. (lets say the file and class name to be executed is named as Student.java)The example program is in the picture background.

Ashwant ManikothAshwant Manikoth

As of Java 9, the JDK includes jshell, a Java REPL.

Assuming the JDK 9+ bin directory is correctly added to your path, you will be able to simply:

  1. Run jshell File.javaFile.java being your file of course.
  2. A prompt will open, allowing you to call the main method: jshell> File.main(null).
  3. To close the prompt and end the JVM session, use /exit

Full documentation for JShell can be found here.

Update Java In Cmd

HorseyHorsey

Now (with JDK 9 onwards), you can just use java to get that executed.In order to execute 'Hello.java' containing the main, one can use: java Hello.java

You do not need to compile using separately using javac anymore.

ShibaShiba

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

akawagucakawaguc

protected by CommunityJan 6 '17 at 12:18

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged java or ask your own question.

Active3 years, 6 months ago

I am trying to execute command line arguments via Java. For example:

The above opens the command line but does not execute cd or dir. Any ideas? I am running Windows XP, JRE6.

(I have revised my question to be more specific. The following answers were helpful but do not answer my question.)

Madhawa Priyashantha
8,5857 gold badges23 silver badges52 bronze badges
joejoe
6,86035 gold badges84 silver badges127 bronze badges

9 Answers

The code you posted starts three different processes each with it's own command. To open a command prompt and then run a command try the following (never tried it myself):

Chulo
5,92911 gold badges47 silver badges69 bronze badges
Peter KnegoPeter Knego
77k9 gold badges115 silver badges142 bronze badges

I found this in forums.oracle.com

Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

You need something like

SyncPipe Class:

tvanfosson
444k86 gold badges660 silver badges762 bronze badges
PepePepe

If you want to run several commands in the cmd shell then you can construct a single command like this:

This page explains more.

Vincent RamdhanieVincent Ramdhanie
91.4k21 gold badges126 silver badges176 bronze badges

Every execution of exec spawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its own working directory and then exit (i.e. it's effectively a no-op).

If you want to compose requests, you'll need to do this within a single call to exec. Bash allows multiple commands to be specified on a single line if they're separated by semicolons; Windows CMD may allow the same, and if not there's always batch scripts.

As Piotr says, if this example is actually what you're trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:

Community
Andrzej DoyleAndrzej Doyle
87.7k28 gold badges177 silver badges219 bronze badges

Try this link

You do not use 'cd' to change the directory from which to run your commands. You need the full path of the executable you want to run.

Also, listing the contents of a directory is easier to do with the File/Directory classes

PiotrPiotr
2,4235 gold badges25 silver badges44 bronze badges

Each of your exec calls creates a process. You second and third calls do not run in the same shell process you create in the first one. Try putting all commands in a bat script and running it in one call:rt.exec('cmd myfile.bat'); or similar

Java Program Tutorials

Carles BarrobésCarles Barrobés
9,6233 gold badges37 silver badges57 bronze badges

This because every runtime.exec(.) returns a Process class that should be used after the execution instead that invoking other commands by the Runtime class

If you look at Process doc you will see that you can use

  • getInputStream()
  • getOutputStream()

on which you should work by sending the successive commands and retrieving the output.

JackJack
113k26 gold badges196 silver badges298 bronze badges

Writing to the out stream from the process is the wrong direction. 'out' in that case means from the process to you. Try getting/writing to the input stream for the process and reading from the output stream to see the results.

Kelly S. FrenchKelly S. French
10.8k8 gold badges51 silver badges88 bronze badges

As i also faced the same problem and because some people here commented that the solution wasn't working for them, here's the link to the post where a working solution has been found.

Also see the 'Update' in the best answer for using Cygwin terminal

Community
singe3singe3
1,1901 gold badge13 silver badges40 bronze badges

How To Execute Java Program In Cmd

Not the answer you're looking for? Browse other questions tagged javaexec or ask your own question.