Run windows exe from java

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.

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

Читайте также:  Анимированные обои для windows 10 машины

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

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.

Jar file as Windows service (+bonus jar to exe)

Aug 22, 2019 · 11 min read

So, your project has lived up to production and you’d like to start it with the OS and you don’t manually rise it every time. But how do we do that with a regular jar-file?

There are a bunch of options:

I) Put the bat-file with java –jar launch or exe-file in Windows startup (after making an exe file from jar).

This will solve the problem, but your a p p will start in the best case only with the first login of any user (if you throw bat into startup for all users). But, as you know, a good admin doesn’t walk on the server.

II) Make the Windows task, starting the bat-file at system startup.

This option perfectly solves startup problem, but the manipulation with the app ends here, neither start-stop at any time, nor restart due to errors.

III) Run jar as win service with sc.exe (there is still Srvinstw.exe — GUI version, but we are true-programmers and must use the command-line).

This is a little program from the Resource Kit for creating services from exe-files.

But we have a jar-file, right?! No problem! There are options to try:

1) Run java.exe -jar with parameters directly.

2) make exe-file from jar and turn it into a service.

a) run java.exe –jar from it

b) write bat-file with launch java -jar and run it from srvany.

IV) Use third-party software.

Let’s rake this pile of options, skipping the first two as the least interesting.

0) Application

First, we’ll write a small application with blackjack and resources, depending on passed parameters, in order to feel maximum pain in the agony of trying to make it work as a service.

— swear that there are no parameters

— read certain setting files depending on the passed parameters

— parse these settings by an external library

— pour the same settings in the log every 5 seconds

An app example can be found here:

My result will be the executable jar-file, with dependent libraries and resources outside in the separate folder. You can do whatever you want, experiment.

1) Start the service with sc.exe

Well, to read sc help, just enter:

The result will be «Error. Unidentified command» and further help on possible commands.

A) Create the service with java.exe –jar

I have a jdk dragging around the app, not to depend on versions in the servers and to give my program solidity of a large size. The full path to java.exe is not necessary if it’s in the environment variables. It’s worth noting one annoying and unobtrusive peculiarity: « binPath= » — after any parameter (here is a binPath) immediately comes the equal sign, and then between it and the parameter value a space is required.

Great, the service is created, run it! Oops.

( My TestService will have different numbers in the examples, because the service wasn’t always deleted immediately, sometimes it was just marked for deletion)

Just in case, let’s look if the app log has appeared. But it has! Only a tiny one, containing info from the moment of trying to start the service up until the moment of issuing the error. What happened? Here’s what:

— service started launching java.exe with the required parameters

— our app started its work

— Windows service manager waited some time for a response from java.exe about it successful (or not) launch

— but java.exe returned nothing, because it owes nothing to anyone

— service manager counted down the timeout in seconds and shot off java

Conclusion: not every exe-file is equally useful to run as a service. One does not simply run any exe-file as a service, it must be specially sharpened for Windows service (at least return some data about it launch).

Or maybe try javaw? Try it, but double-V in the name doesn’t mean double victory.

B) Create the service with cmd /c java.exe -jar

What if you run cmd in cmd in cmd and in it run java? Will the whole chain close? Let’s start small — run only java from the cmd, and specify cmd as binpath at service start:

Likewise, it falls off after the timeout. But only the cmd process ends its worthless life, and our mega java app continues to breathe and delight.

It works? Yes! As a full service? No toothing way!

But put our jar-file in a folder with spaces to (“escape”) enjoy the creation of inclined sticks next to quotes a little more:

Look at the registry:

Doesn’t look bad, just parameters should be crammed in quotation marks for complete happiness.

Conclusion: tricks are good, but not always 100% useful.

C) Create the service with srvany.exe java.exe –jar

srvany.exe is also a program tool from the Resource Kit. Its work is simple — run the specified app. I.e. we register srvany.exe as a service with parameters indicating the path to our program. Order: start the service → run srvany → run our app.

Add parameters to launch srvany:

Starting.. watching.. waiting.. watching.. it works!! It’s all? This is the end? Or is something missing? Why invented third-party software (except of self-education and advertising purposes)? You can try to kill the process or invoke the exception in the app. And we will smoothly proceed to the next point.

Conclusion: srvany works, but catching errors is lame.

2) Start the service with third-party software NSSM.

Here is a short list of different software:

— jsvc (pervert’s version: « It can run on Win32 via the Cygwin emulation layer» (с))

We’ll use the last one. For lazy readers repeat the question: why do we need a third-party software? For them, the answer is right from the nssm site:

«srvany and other service helper programs suck because they don’t handle failure of the application running as a service. If you use such a program you may see a service listed as started when in fact the application has died. nssm monitors the running service and will restart it if it dies.»

How does it work? All the same: nssm.exe installing as a service with specified parameters, when the service starts — nssm.exe itself starts, which in turn launches java.exe –jar. Here is a clear run in the task manager for you:

Now in order. Execute « nssm.exe install TestServ » to start the GUI.

We can do the same using the command line:

it’s important for us to indicate AppDirectory, because the configs and libs used by us lie there, next to our app in the resources and res subfolders.

If you are tired of the service or you screwed up when creating it, then run the command:

Let’s look back-to-back at the registry entries:

All parameters and quotation marks are in place. Look at the service info:

Run service.. Hurray! Everything works, logs are written!

Try to kill java or crash your application from the inside.

Conclusion: not written by our magnificent hands, brains and legs third-party software also has the right to life.

3) Automate it!

It’s worthless to start services on 30 servers by handles, the script is necessary! Omit spreading on machines, at least let’s create a service to correctly run the configuration designated on current server just with one variable name change.

But the script is easy! Sure? And if you add spaces in the names? The pain is hiding in details of fine-tuning quotation marks and their escaping. Suppose we put AppDir into a variable. How should we write it in the params and as the current directory? Where are the quotation marks necessary and where not?

use in parameters:

as the current directory:

If configured incorrectly, you can get such an error when starting the service:

Go to system event log for details:

See what’s wrong with registry paths:

Based on the results we draw conclusions about superfluous/missing quotes or slashes in the right places.

The result script looks like this:

And in the params in the registry:

Let’s test restarting. Run app with throwing an exception in a parallel thread, that the app terminates itself after two iterations.

Watch log files, see their re-creation, which means the service restarts our app upon completion. Great! Even logs are presented in the System Event Journal with a source nssm:

Service TestServ ran for less than 1500 milliseconds. Restart will be delayed by 2000 milliseconds.

Conclusion: Automate everything you need, not everything you can, otherwise it may take more time for useless work.

4) Bonus: jar to exe

Now let’s try to convert/wrap/shove our jar-file into exe-file and run it as a service.

Here is a couple of variants:

I haven’t tried it yet, there are a lot of opportunities there, but it’s a bit confusing for our purposes now.

C) Launch4j — standalone program or as a maven plugin.

Use standalone launch4j.

Fill the GUI form and specify path to jar and its params, try to embed JDK inside:

However, it can’t be started, the “start” button is unhighlighted. What’s wrong? Try to save the settings and run it from the cmd:

Oh yea, it’s not visible on the screenshot, but I played around firstly and indicated the jre max version as 9, but it needs to be 11. Erase jre version, run, get:

Erm.. add to the Boundled JRE Path — «\javaw.exe». Doesn’t work. Erase javaw and bin folder. Voila! But wait, now run the exe-file:

Aaarrrgh.. it must be a fat jar.. Okay, move the resources folder. Launch.. Yeah it works!

It can be seen from the running processes that in our case mainTut.exe — is just a wrapper, that launches java-exe –jar with params. Moreover, in the “path to jar” argument is mainTut.exe itself! Let’s try to open our exe-file with the archiver:

Actually, here lies the same thing as in our jar-file.

One point — we allegedly have a built-in JRE, although it’s not noticeable by size and the archive inside. Let’s try to rename jdk folder for verification. That is, it doesn’t work. We’ll not be tormented with all the relations, the main thing — here is a working variant and it’s necessary to test it as a service.

but the result is disappointing, like from the cmd — mainTut.exe closes, but java.exe remains. + somehow it’s necessary to throw different arguments to a jar, cause they are sewn into exe-file.

Conclusion: the simple wrapping of your jar-file in exe will not give you any profit to run it as a service. And no profit at all. The wrapping makes sense rather for assembling an installation package.

General conclusion.

Use NSSM to launch jar-file as a service and enjoy the uptime!

Feel free to shake hand on Medium or Telegram or Twitter.

Читайте также:  Windows для samsung gt s7530
Оцените статью