How to run a jar file on windows 10. Working with Java on the command line

Antipyretics for children are prescribed by a pediatrician. But there are emergency situations for fever when the child needs to be given medicine immediately. Then the parents take responsibility and use antipyretic drugs. What is allowed to give to infants? How can you bring down the temperature in older children? What medicines are the safest?

Many novice programmers are faced with the following question: "I created my application in the IDE, now how do I make it work from the command line outside the IDE?". Another question that might arise is, "How can I distribute this application to other users without giving them the entire IDE at the same time?".

The answers to these questions are relatively simple, but not always obvious. AT this document answers them by demonstrating the basics of using the IDE to prepare applications for distribution and deployment. In addition, this document provides information that may be needed to set up a programmer's system (or that will need to be communicated to users of the application). We will show several different approaches to deploying an application, allowing users to access it through:

  • Double-clicking the application's Java archive (JAR) file.
  • Calling an application from the command line.
  • Calling an application from a script file.
  • Using Java Web Start.

This tutorial requires the software and materials listed in the table below.

Creating an executable JAR file

This part of the tutorial shows you how you can create a redistributable application in the IDE and then run the application outside the IDE. We package this application into an executable JAR file.

A JAR file is an archive file that can contain files and folders. JAR files are similar to ZIP files, but JAR files can have additional attributes that are useful when distributing Java applications. These attributes include the digital signature of JAR files, optional compression, cross-platform compatibility, and so on.

In this exercise, we create an IDE project and then place two pre-written Java source files into the project. We will then compile the classes and create an executable JAR file. After that, we'll see how to run JAR files outside of the IDE.

The classes used in this tutorial implement the functions of the GNU grep utility, which can be used to search for text or regular expression patterns in text files. This project contains both a command line version of the application and a version that uses GUI, which will give you a look at the different ways to run the application.

Building a Project Using Existing Source Code Files

  1. Distributing the application to other users

    Now that you've confirmed that your application works outside of the IDE, you can move on to distributing it.

    Note. If your application depends on additional libraries other than those included in the JDK, you must include them in your distribution (does not apply to this example). Relative paths to these libraries are added to the classpath entry of the JAR manifest file when the application is developed in the IDE. If these additional libraries are not found in the specified class path (i.e. relative path) at startup, the application will not start.
    Create ZIP archive containing the JAR file and library, and then upload this ZIP file users. Instruct users to unpack this ZIP archive so that the JAR file and library JAR files are in the same folder. Run the application jar file.

    Launching a Java Application

    The purpose of this exercise is to demonstrate some of the ways to run an application from the command line.

    This exercise shows how you can start a Java application in the following two ways:

    • Running a java command from the command line.
    • Using a script to call a class in a JAR file.

    Launching applications from the command line

    The application can be launched from the command line using the java command. If you want to execute an executable JAR file, use the -jar option of the command.

    For example, to run the AnotherGrep application, do the following:

    1. Open a terminal window. On Microsoft Windows systems, this is done by clicking the "Start" button and selecting "Run...", typing cmd in the "Open:" field, and clicking the "OK" button.
    2. Go to directory PROJECT_HOME/dist (using the cd command).
    3. Enter the following line to run the main application class: java -jar AnotherGrep.jar

    If you follow these instructions and the application does not start, you should probably do one of the following:

    Launching Applications from a Script

    If the application you want to distribute is a console application, you may find it more convenient to run it from a script, especially if the application requires long and complex arguments to run. In this section, we use the console version of Grep, in which we need to pass arguments (a search pattern and a list of files) to the JAR file called in our script. To reduce the amount of typing at the command line, we use a simple script suitable for running a test application.

    The first step is to change the main class in the application to the console version of the class and rebuild the JAR file:

    1. In the IDE's Projects window, right-click the project node (AnotherGrep) and select Properties.
    2. Select the Run node and change the Main Class property to anothergrep.Grep (from anothergrep.xGrep). Click the OK button to close the Project Properties window.
    3. Right-click the project node again and select Clean and Build Project.

    When these steps are complete, the JAR file will be rebuilt and the Main-Class attribute in the JAR file's manifest will point to anothergrep.Grep .

    bash script - for computers running UNIX and Linux

    In the folder where the contents of the file were extracted, you can find a bash script named grep.sh . Let's take a look at it:

    #!/bin/bash java -jar dist/AnotherGrep.jar [email protected]

    The first line specifies which command interpreter to use to interpret this script. The second executes the JAR file created by the IDE in the folder PROJECT_HOME/dist . [email protected] simply copies all the arguments passed to the script, enclosing each one in quotes.

    This script assumes that the Java binaries are part of the PATH environment variable. If this script does not work on your computer, see .

    For more information on scripting the bash interpreter, see .

    .bat script for Windows computers

    On Microsoft Windows computers, a maximum of nine arguments can be passed to batch files at a time. If there are more than nine arguments, the JAR file will need to be executed multiple times.

    The script for this might look like this:

    @echo off set jarpath="dist/AnotherGrep.jar" set pattern="%1" shift:loop if "%1" == "" goto:allprocessed set files=%1 %2 %3 %4 %5 %6 %7 %8 %9 java -jar %jarpath% %pattern% %files% for %%i in (0 1 2 3 4 5 6 7 8) do shift goto:loop:allprocessed

    This script can be found under the name grep.bat in the folder where the contents of the archive were extracted, if you want to see it in action.

    The nine arguments are provided inside the batch file as % , where must have a value within<0-9>. %0 is reserved for script name.

    You can see that only nine arguments are passed to the program at a time (in one loop). The for statement simply shifts the arguments by nine to prepare them for the next loop. The loop terminates when an empty file argument is found by the if statement (this indicates that there are no new files to process).

    More information about batch scripting can be found at .

    Packaging an Application for Java Web Start

    Java Web Start is a technology used to launch Java applications from a web browser with a single click. See Enabling Java Web Start in NetBeans IDE for details on packaging applications for deployment with Java Web Start. Here, we only provide a brief description of the steps required to make an application deployable using Java Web Start.

    1. Right-click the project node in the Projects window and select Properties.
    2. On the Web Start tab of the Project Properties window, select the Enable Web Start check box.
    3. Select Local Execution from the Codebase dropdown as we will only be testing local execution.
      Keep all other default settings and click OK.
    4. Right-click the project node and select Clean and Build Project.
      This IDE command will remove all previously compiled files and builds, recompile the application, and build the project with the new settings.
    5. Outside the IDE, open the folder PROJECT_HOME/dist , then open the launch.html file in your browser.
      A test will appear. HTML page with the Launch button.
    6. Press the Launch button to open the app.
      You will be able to see that Java is loaded and the application is running.

      Note. Some browsers first redirect users to the Java downloads page.

    Specifying JAR File Associations

    On most computers, an executable JAR file can be executed simply by double-clicking it. If nothing happens when you double-click a JAR file, it could be due to one of the following two reasons:

    • The JAR file type is not associated with the Java Runtime Environment (JRE) on this computer.

      If the JAR file type is associated with a JRE, the icon representing that file must include the Java logo.

    • The JAR file type is mapped to the JRE, but the -jar option is not part of the command passed to the JRE when the icon is double-clicked.

    Note. Sometimes JAR file associations are switched by installed software, for example, software to process zip files.

    The way that a JAR file type can be bound to a java launcher depends on the operating system.

    Make sure you have one of the JRE versions installed on your computer. Version 1.4.2 or later should be used. Java applications cannot be run on computers that do not have the Java platform installed. (If a Java Development Kit (JDK) is installed, the JRE is also installed with it. However, if the program is distributed to non-programmers, users may not have the JRE or JDK.)

    • On Windows XP installed Java version can be checked by selecting "Start" > "Control Panel" > ("Add or Remove Programs") (there should be, for example, Java (TM) 6 Update 33).
    • On the Windows Vista or 7 installed version of Java can be checked by selecting "Start" > "Control Panel" > ("Programs and Features") (there should be specified, for example, Java (TM) 6 Update 33).

    If your computer does not have the Java platform, the JRE can be downloaded from the Java SE download site.

    If you already have it on your computer, but the file association does not work, follow the steps to add the JAR file association in Microsoft Windows:

    1. Select "Start" > "Control Panel".
    2. (Applies to Windows Vista only). Click "Control Panel" > "Programs".

    3. For Windows Vista or 7, click Default Programs and select Associate a file type or protocol with a program.
    4. (In Windows XP, in the Details section of the dialog box, click Change Program.)
    5. In the Program Selection dialog box, select Java Platform SE Binary.
    6. Click the "OK" button to exit the "Select Program" dialog box.
    7. Click the Close button to close the Folder Options dialog box (in Windows XP) or the dialog box for associating a file type or protocol with specific programs (in Windows 7).

    Note. If JAR files are associated with the Java Platform SE Binary on the system, but double-clicking still does not launch the JAR file, you may need to specify the -jar option on the file association.

    To specify the -jar option in the file association on Microsoft Windows XP, follow these steps:

    1. Select "Start" > "Control Panel".
    2. In Windows XP, double-click "Folder Options" and select the "File Types" tab.
    3. In the Registered File Types list, select the JAR file.
    4. In the Details section of the dialog box, click Advanced.
    5. In the Edit File Type Properties dialog box, click Edit....
    6. In the "Application that executes the action" text box, add the following line to the end of the JRE path: -jar "%1" %* After that, the box should contain text similar to the following: "C:\Program Files\Java\jre1.6.0_33\ bin\javaw.exe" -jar "%1" %*
    7. Click OK to exit the Change Type Action dialog box.
    8. Click OK to exit the Edit File Type Properties dialog box.
    9. Click the Close button to exit the Folder Options dialog box.

    Note. Beginning with Windows Vista, extended file associations can be configured using RegEdit. For more information, see What happened to the file types dialog? .

    For UNIX and Linux systems, the procedure for changing file associations depends on which desktop environment (such as GNOME or KDE) is being used. Take a look at your workspace settings or read the workspace documentation.

    Setting the PATH environment variable

    If your computer cannot run a Java class or JAR file without specifying the location of the JDK or JRE, you may need to change the value of the system PATH environment variable.

    When running on a Microsoft Windows system, the procedure for setting the PATH variable depends on the version of Windows that you are using.

    Following are the steps to set PATH variable to Windows system XP:

    1. Select "Start" > "Control Panel" and double-click "System".
    2. In the System Properties dialog box, select the Advanced tab.
    3. Click the Environment Variables tab.
    4. In the list of user environment variables, select PATH and click the Edit button.
    5. Add the JRE location to the end of the path list. The locations in the list are separated by semicolons (;).
      For example, if the JRE is located in C:\Program Files\Java\jdk1.6.0_23, then add the following to the end of the PATH variable: C:\Program Files\Java\jdk1.6.0_23\bin
    6. Click OK to exit the Environment Variables dialog box, then click OK to exit the System Properties dialog box.

    When working in operating system UNIX or Linux, the way you change the PATH environment variable depends on the command interpreter program you are using. See the command interpreter documentation for more information.

    What's next?

    For more information about working with the NetBeans IDE, see the NetBeans website.

    More information about Java application development in the IDE, including classpath management, is available in the document

Now no one creates programs in the console. Using your favorite IDE, the developer feels uncomfortable at someone else's computer, where it is not.
Deciding to understand the work of Ant and Maven, I found myself unable to build the application without them in the console.
In this article, I tried to fit all the stages of designing a demo application so as not to look for help on each command on the Internet.

From simple to...

Each program is usually contained in a separate directory. My rule is to create at least two folders in this directory: src and bin. The first contains the source codes, the second contains the compilation result. These folders will have a directory structure depending on the packages.

One file

You can do it without extra folders.
Let's take the file.
01 02 03 04 05 06 07 08 09 public class HelloWorld ( public static void main(String args) ( System.out.println("Hello World!"); Calculator calc=new Calculator(); System.out.println("2+2="+calc.sum (2,2)); ) )
Go to the directory where this file is located and execute the commands.
javac HelloWorld.java The HelloWorld.class file will appear in this folder. So the program is compiled. To start it
java -classpath . hello world

Separating binaries from sources

Now we will do the same, but with directories. Let's create a HelloWorld directory with two folders src and bin in it.
Compiling
javac -d bin src/HelloWorld.java Here we have indicated that the binaries will be saved in a separate bin folder and not be confused with the sources.

We launch
java -classpath ./bin HelloWorld

We use packages

And then, suddenly, the program will cease to be just HelloWorld. Packages are best given a meaningful and unique name. This will add this program to another project with no naming conflict. After reading some of the articles, you might think that the package name necessarily needs a domain. This is not true. Domains are a convenient way to achieve uniqueness. If you do not have your own domain, use an account on the site (for example, ru.habrahabr.mylogin). It will be unique. Please note that package names must be in lower case. And avoid using special characters. Problems arise due to different platforms and file systems.

Let's place our class in a package called com.qwertovsky.helloworld. To do this, add a line to the beginning of the file
package com.qwertovsky.helloworld; Let's create additional directories in the src directory so that the path to the file looks like this: src/com/qwertovsky/helloworld/HelloWorld.java.
Compiling
javac -d bin src/com/qwertovsky/helloworld/HelloWorld.java The bin directory will automatically have a directory structure similar to src.
HelloWorld "---bin " "---com " "---qwertovsky " "---helloworld " "---HelloWorld.class "---src "---com "---qwertovsky "-- -helloworld "---HelloWorld.java Run
java -classpath ./bin com.qwertovsky.helloworld.HelloWorld

If there are several files in the program

Let's change the program. Pay no attention to logic. She is not.
HelloWorld.java
01 02 03 04 05 06 07 08 09 10 11 12 13 package com.qwertovsky.helloworld; public class HelloWorld ( public static void main(String args) ( int a=2; int b=3; Calculator calc=new Calculator(); System.out.println("Hello World!"); System.out.println( a+"+"+b+"="+calc.sum(a,b)); ) )
Calculator.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 package com.qwertovsky.helloworld; import com.qwertovsky.helloworld.operation.Adder; public class Calculator ( public int sum(int... a) ( Adder adder=new Adder(); for(int i:a) ( adder.add(i); ) return adder.getSum(); ) )
Adder.java
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package com.qwertovsky.helloworld.operation; public class Adder ( private int sum; public Adder() ( sum=0; ) public Adder(int a) ( this.sum=a; ) public void add(int b) ( sum+=b; ) public int getSum() ( return sum; ) )
Compiling
javac -d bin src/com/qwertovsky/helloworld/HelloWorld.java src\com\qwertovsky\helloworld\HelloWorld.java:9: cannot find symbol symbol: class Calculator location: class com.qwertovsky.helloworld.HelloWorld Calculator calc=new calculator(); ^ src\com\qwertovsky\helloworld\HelloWorld.java:9: cannot find symbol symbol: class Calculator location: class com.qwertovsky.helloworld.HelloWorld Calculator calc=new Calculator(); ^ 2 errors The error occurred due to the fact that files with source codes of the classes that are used (the Calculator class) are needed for compilation. You must specify the directory with the files to the compiler using the -sourcepath key.
Compiling
javac -sourcepath ./src -d bin src/com/qwertovsky/helloworld/HelloWorld.java Run
java -classpath ./bin com.qwertovsky.helloworld.HelloWorld Hello Word 2+3=5

If you are surprised by the result

It is possible to launch a debugger. That's what jdb is for.
First, we compile with the -g switch so that the debugger has information.
javac -g -sourcepath ./src -d bin src/com/qwertovsky/helloworld/HelloWorld.java Start the debugger
jdb -classpath bin -sourcepath src com.qwertovsky.helloworld.HelloWorld Initializing jdb ... > The debugger launches its internal terminal to enter commands. Help on the latter can be displayed using the help command.
Set a breakpoint on line 9 in the Calculator class
> stop at com.qwertovsky.helloworld.Calculator:9 Deferring breakpoint com.qwertovsky.helloworld.Calculator:9. It will be set after the class is loaded. We launch for execution.
> run run com.qwertovsky.helloworld.HelloWorld Set uncaught java.lang.Throwable Set deferred uncaught java.lang.Throwable > VM Started: Set deferred breakpoint com.qwertovsky.helloworld.Calculator:9 Hello World! Breakpoint hit: "thread=main", com.qwertovsky.helloworld.Calculator.sum(), line=9 bci=0 9 Adder adder=new Adder(); To get your bearings, you can display a piece of source code where the cursor is currently located.
main list 5 public class Calculator 6 ( 7 public int sum(int... a) 8 ( 9 => Adder adder=new Adder(); 10 for(int i:a) 11 ( 12 adder.add(i); 13) 14 return adder.getSum(); Find out what the variable a is.
main print a a = instance of int (id=340) main dump a a = ( 2, 3 ) main stop at com.qwertovsky.helloworld.operation.Adder:19 Deferring breakpoint com.qwertovsky.helloworld.operation.Adder:19. It will be set after the class is loaded. Let's continue execution.
main cont > Set deferred breakpoint com.qwertovsky.helloworld.operation.Adder:19 Breakpoint hit: "thread=main", com.qwertovsky.helloworld.operation.Adder.add(), line=19 bci=0 19 sum+=b ; main list 15 ) 16 17 public void add(int b) 18 ( 19 => sum+=b; 20 ) 21 22 public int getSum() 23 ( 24 return sum; main print sum sum = 0 main print b b = 2 in the current line and see that sum has become equal to 2.
main step > Step completed: "thread=main", com.qwertovsky.helloworld.operation.Adder.add(), line=20 bci=10 20 ) main print sum sum = 2 Let's ascend from the Adder class to the Calculator class that called it.
main step up > Step completed: "thread=main", com.qwertovsky.helloworld.Calculator.sum(), line=10 bci=36 10 for(int i:a) Remove breakpoint
main clear com.qwertovsky.helloworld.operation.Adder:19 Removed: breakpoint com.qwertovsky.helloworld.operation.Adder:19 main step > Step completed: "thread=main", com.qwertovsky.helloworld.Calculator.sum() , line=12 bci=30 12 adder.add(i); You can avoid stepping into methods by using the next command.
main next > Step completed: "thread=main", com.qwertovsky.helloworld.Calculator.sum(), line=10 bci=36 10 for(int i:a) main next > Step completed: "thread=main", com.qwertovsky.helloworld.Calculator.sum(), line=14 bci=42 14 return adder.getSum(); We check the value of the expression and complete the execution.
main eval adder.getSum() adder.getSum() = 5 main cont > 2+3=5 The application exited

Would be nice to test

We use JUnit.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.qwertovsky.helloworld; import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; @RunWith(value=org.junit.runners.Parameterized.class) public class TestCalculator ( int expected; int arg; @Parameters public static Collection parameters() ( return Arrays.asList(new int( ((4), (2, 2)) ,((-1),(4, -5)) ,((0),(0,0,0) ) ,((0),()) )); ) public TestCalculator(int expected, int arg) ( this.expected=expected; this.arg=arg; ) @Test public void testSum() ( Calculator c=new Calculator (); assertEquals(expected,c.sum(arg)); ) )
Compiling
mkdir test_bin javac -classpath lib/path/junit-4.8.2.jar -sourcepath ./src -d test_bin test/com/qwertovsky/helloworld/TestCalculator.java Run. The classpath separator on Windows is ";", on Linux it is ":". Both delimiters don't work in Cygwin console. Maybe ";" should work, but it's treated as a command separator.
java -classpath lib/path/junit-4.8.2.jar:./test_bin org.junit.runner.JUnitCore com.qwertovsky.helloworld.TestCalculator JUnit version 4.8.2 .... Time: 0.031 OK (4 tests)

Let's create a library

The Calculator class has proven to be useful and can be used in many projects. Let's move everything related to the Calculator class to a separate project.
HelloWorld "---bin "---src "---com "---qwertovsky "---helloworld "---HelloWorld.java Calculator "---bin "---src ""---com " "---qwertovsky " "---calculator " "---Calculator.java " "---operation " "---Adder.java "---test "---com "---qwertovsky " ---calculator "---TestCalculator.java Also change the names of the packages in the sources. In HelloWorld.java you will need to add the line
import com.qwertovsky.calculator.Calculator; Compiling.
cd Calculator javac -sourcepath src -d bin src/com/qwertovsky/calculator/Calculator.java Making a jar archive
jar cvf calculator.jar -C bin . added manifest adding: com/(in = 0) (out= 0)(stored 0%) adding: com/qwertovsky/(in = 0) (out= 0)(stored 0%) adding: com/qwertovsky/calculator/ (in = 0) (out= 0)(stored 0%) adding: com/qwertovsky/calculator/Calculator.class(in = 497) (out= 373)(deflated 24%) adding: com/qwertovsky/calculator/operation /(in = 0) (out= 0)(stored 0%) adding: com/qwertovsky/calculator/operation/Adder.class(in = 441) (out= 299)(deflated 32%) run the program in the bin directory.

We need to find out what the library has inside

You can unpack the archive with a zip-unpacker and see what classes are in the library.
Information about any class can be obtained using the javap disassembler.
javap -c -classpath calculator.jar com.qwertovsky.calculator.Calculator Compiled from "Calculator.java" public class com.qwertovsky.calculator.Calculator extends java.lang.Object( public com.qwertovsky.calculator.Calculator(); Code : 0: aload_0 1: invokespecial #1; //Method java/lang/Object." ":()V 4: return public int sum(int); Code: 0: new #2; //class com/qwertovsky/calculator/operation/Adder 3: dup 4: invokespecial #3; //Method com/qwertovsky /calculator/operation/Adder." ":()V 7: astore_2 8: aload_1 9: astore_3 10: aload_3 11: arraylength 12: istore 4 14: iconst_0 15: istore 5 17: iload 5 19: iload 4 21: if_icmpge 42 24: aload_3 25: iload 5 27: iaload 28: istore 6 30: aload_2 31: iload 6 33: invokevirtual #4; //Method com/qwertovsky/calculator/operation/Adder.add:(I)V 36: iinc 5, 1 39: goto 17 42 : aload_2 43: invokevirtual #5; //Method com/qwertovsky/calculator/operation/Adder.getSum:()I 46: ireturn the add method of the Adder class is called.After the sum method completes, Adder.getSum() is called.
Without the -c switch, the program will only give a list of variables and methods (if you use -private, then all).
javap -private -classpath calculator.jar com.qwertovsky.calculator.operation.Adder Compiled from "Adder.java" public class com.qwertovsky.calculator.operation.Adder extends java.lang.Object( private int sum; public com.qwertovsky .calculator.operation.Adder(); public com.qwertovsky.calculator.operation.Adder(int); public void add(int); public int getSum(); )

It's better to document the library

Let's change the calculator class for this.
Documentation can be generated with the following command. If an error occurs, the program will display a list of possible options.
mkdir doc javadoc -d doc -charset utf-8 -sourcepath src -author -subpackages com.qwertovsky.calculator

jar archive can be signed

If you need to sign your library with a digital signature, keytool and jarsigner will come to the rescue.
We generate a signature.
keytool -genkey -keyalg rsa -keysize 2048 -alias qwertokey -keystore path/to/qwerto.keystore Enter keystore password: Re-enter new password: What is your first and last name? : Valery Qwertovsky What is the name of your organizational unit? : Qwertovsky What is the name of your organization? : Qwertovsky What is the name of your City or Locality? : Tver What is the name of your State or Province? : Tverskaya obl. What is the two-letter country code for this unit? : RU Is CN=Valery Qwertovsky, OU=Qwertovsky, O=Qwertovsky, L=Tver, ST=Tverskaya obl., C=RU correct? : y Enter key password for (RETURN if same as keystore password): Re-enter new password:
Generating a Certificate Signing Request (CSR)
keytool -certreq -file path/to/qwertokey.crt -alias qwertokey -keystore path/to/qwerto.keystore Send the contents of the received file to the certification authority. We receive a certificate from the certification authority. We save it in a file (for example, qwertokey.cer) and import it into the repository
keytool -import -trustcacerts -keystore path/to/qwert.keystore -alias qwertokey -file path/to/qwertokey.cer Sign the jar archive
jarsigner -keystore path/to/qwerto.keystore calculator.jar qwertokey We send the qwertokey.cer file to anyone who wants to check the archive. It is checked like this
jarsigner -verify -verbose -certs -keystore path/to/qwerto.keystore calculator.jar

Using the library

There is a HelloWorld program that uses the Calculator library class. To compile and run the program, you need to include the library.
Compiling
cd HelloWorld javac -sourcepath src -d bin -classpath path/to/calculator.jar src/com/qwertovsky/helloworld/HelloWorld.java Run
java -classpath bin:path/to/calculator.jar com.qwertovsky.helloworld.HelloWorld

Putting together the program

This can be done in different ways.

First way

cd HelloWorld echo main-class: com.qwertovsky.helloworld.HelloWorld>manifest.mf echo class-path: lib/calculator.jar >>manifest.mf mkdir lib cp path/to/calculator.jar lib/calculator.jar jar - cmf manifest.mf helloworld.jar -C bin . There are subtleties here.
In line
main-class: com.qwertovsky.helloworld.HelloWorld should not have trailing spaces.
The second subtlety is described in: in the same line there should be a transfer to the next line. This is if the manifest is archived by a third-party archiver.
The jar program will not include the last line from the manifest in the manifest unless there is a line break at the end.
Another point: in the manifest there should not be empty lines between the lines. An error "java.io.IOException: invalid manifest format" will be thrown.

When using the echo command, you only need to watch the space at the end of the main-class line.

Second way

cd HelloWorld echo class-path: lib/calculator.jar >manifest.mf mkdir lib cp path/to/calculator.jar lib/calculator.jar jar -cmef manifest.mf com.qwertovsky.helloworld.HelloWorld helloworld.jar -C bin . In this way, we avoid the error with a space in main-class.

Third way

cd HelloWorld mkdir lib cd lib jar -xvf path/to/calculator.jar com/ created: com/ created: com/qwertovsky/ created: com/qwertovsky/calculator/ inflated: com/qwertovsky/calculator/Calculator.class created: com /qwertovsky/calculator/operation/ inflated: com/qwertovsky/calculator/operation/Adder.class cd .. cp -r bin/* lib/ jar -cef com.qwertovsky.helloworld.HelloWorld helloworld.jar -C lib . rm -r lib Include the required library code in the executable.

Running the executable jar file

The calculator.jar file is not executable. But helloworld.jar can be run.
If the archive was created in the first two ways, then next to it in the same directory there should be a lib folder with the calculator.jar file. Such restrictions are due to the fact that the path relative to the executable file is specified in the class-path in the manifest.
cd Calculator ls ../HelloWorld/lib calculator.jar java -jar ../HelloWorld/helloworld.jar The third method includes the required libraries in the executable. You do not need to keep the necessary libraries nearby. Runs the same way.
java -jar ../HelloWorld/helloworld.jar

How to deal with JavaEE applications

Likewise. Only libraries for compilation need to be taken from the application server that is being used. If I'm using JBoss, then to compile the servlet I would need to do something like this
javac -classpath path/to/jboss/common/lib/jboss-servlet*.jar -d ./classes src/com/qwertovsky/app/servlets/MenuSt.java
The structure of a JavaEE application archive must follow a certain format. For example
my.ear `---META-INF | `---manifest.mf `---lib | `---mylib.jar `---my.war | `---META-INF | | `---manifest.mf | `---WEB-INF | | `---lib | | | `---myweblib.jar | | `---classes | | | `---com | | | `---... | | `---web.xml | `---index.html | `---<остальное веб-содержимое (страницы, изображения)>`---myejb.jar
The way to run the application on the server itself using the command line is different for each server.

I hope this article will become for someone a cheat sheet for working with Java in command line. These skills will help you understand the content and meaning of Ant scripts and answer more tricky interview questions than “Which IDE do you like best?”.

Now I will show how you can run a simple java program without any environment like an application server. One class is enough, in which the main method will be defined.

package com.blogspot;
public class DeveloperRemarks(
public static void main(String args) (
if (args.length == 0) (
System.out
.println("Pass as command line parameter the text you want to see.");
) else (
System.out.println("You entered: " + args);
}
System.out.println("Source available at developer-remarks.blogspot.com");
}
}
In the command line, when starting the program, you must pass the text that will be displayed on the screen. Otherwise, a corresponding message will be displayed. All parameters passed to the program will be contained in the args array of strings that the main method accepts. If no parameters are passed, the length of the array will be zero.

Now let's configure Eclipse to be able to run the jar file from the terminal. To do this, you first need to create a run configuration. Select Run - Run Configurations from the top menu. The following window will open:

In the list on the left, select the application type: Java Application. There, create a new configuration as shown in the screenshot. To do this, select the target project and the class that has the main method.

We are now ready to export our project into an executable jar file. To do this, click on the project with the right mouse button, select "Export ...", the following window will open:


Select Runnable Jar file from the tree view. The search can be greatly simplified if you filter the project type by name. Click Finish. After that, a window for export settings will open:


In it, select the previously created launch configuration. Then provide the full name of the jar file. In the "Library handling" section, select "Extract required libraries into generated JAR" (unpack the required libraries into the generated archive). Click Finish and the executable archive will be created.

Since in this example there are no dependencies on other libraries, we choose the first item. But if we had several tens or even hundreds of dependencies, it would be more correct to select the third item "Copy required libraries into a sub-folder next to the generated JAR" (copy the required libraries into a subdirectory, part of the name of which matches the archive being created ) to avoid "bloating" the executable. If we had chosen the third item, the necessary libraries would have been copied to a separate folder.

Now open a terminal and navigate to the directory where the executable jar was created. Enter the following command:

java -jar developer-remarks.jar hello world!

This is how you tell the java interpreter to run our archive. Note that the space and exclamation mark on the command line must be escaped with a backslash.

The demonstrated approach can be useful for educational and testing purposes. For example, to create a client that will call the EJB and print the result of its work to the console. The advantage of this approach is the launch of the jar archive without any kind of environment. It is enough to have a JDK/JRE. Sources are available.

Task: Run a java application from the command line.

For example, I made a small program that should calculate the area of ​​a circle for a given radius. The program contains two classes: GeometryWF (main) and Circle. It is supposed to create a console application. Starting a java application must be done from the command line.

package geometrywf;
public class GeometryWF(
public static void main(String args) (
try(
if (args. equals("circle")) (
Circle c = new Circle(Double.parseDouble(args));
System.out.println("Circle perimetre: "+c.perimeter());
System.out.println("Circle aria: "+c.area());
}
}
catch(ArrayIndexOutOfBoundsException e) (
System.out.println("Invalid input parameters!");
}
}
}

package geometrywf;
public class Circle(
public double r = 0;
public Circle(double r) (
this.r = r;
}
public double area() (
return(Math.PI*r*r);
}
public double perimeter() (
return(2*Math.PI*r);
}
}

The next step is to build the project. I use NetBeans IDE for development. Accordingly, the assembly is carried out by pressing the combination "Shift + F11" ("Clear and build the project"). As a result, I get a finished jar file
(C:\Users\Jan\Documents\NetBeansProjects\GeometryWF\dist\GeometryWF.jar).

Launch from command line.

Before launching the command prompt, right-click on the "My Computer" icon and open "Properties". Go to "Advanced system settings"->"Environment variables". In the "System Variables" section, you need to create a new variable "JAVA_HOME" with the value "" (I have it "C:\glassfish3\jdk\bin"). The same path must be written in the existing Path variable after the semicolon. We save everything and run the command line.

We change the directory to the folder with the jar file using the CHDIR command:

C:\Users\John> CHDIR C:\Users\John\Documents\NetBeansProjects\GeometryWF\dist\

We launch the java application from the command line using the command "java -jar .

C:\Users\John\Documents\NetBeansProjects\GeometryWF\dist> java -jar GeometryWF.jar circle 9

At the output we get:

Circle perimetre: 56.548667764616276
Circle square: 254.46900494077323



Support the project - share the link, thanks!
Read also
cockfight game rules cockfight game rules Mod for minecraft 1.7 10 watch recipes.  Recipes for crafting items in Minecraft.  Weapons in Minecraft Mod for minecraft 1.7 10 watch recipes. Recipes for crafting items in Minecraft. Weapons in Minecraft Shilling and sterling - the origin of words Shilling and sterling - the origin of words