How to create jar file intellij idea
How to create jar file intellij idea
Create your first Java application
In this tutorial, you will learn how to create, run, and package a simple Java application that prints Hello, World! to the system output. Along the way, you will get familiar with IntelliJ IDEA features for boosting your productivity as a developer: coding assistance and supplementary tools.
Watch the screencast and follow the step-by-step instructions below:
Prepare a project
Create a new Java project
In IntelliJ IDEA, a project helps you organize your source code, tests, libraries that you use, build instructions, and your personal settings in a single unit.
Launch IntelliJ IDEA.
In the New Project wizard, select New Project from the list on the left.
Name the project (for example HelloWorld ) and change the default location if necessary.
We’re not going to work with version control systems in this tutorial, so leave the Create Git repository option disabled.
To develop Java applications in IntelliJ IDEA, you need the Java SDK ( JDK ).
If the necessary JDK is already defined in IntelliJ IDEA, select it from the JDK list.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory (for example, /Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk ).
After that, the IDE will create and load the new project for you.
Create a package and a class
Packages are used for grouping together classes that belong to the same category or provide similar functionality, for structuring and organizing large applications with hundreds of classes.
IntelliJ IDEA creates the com.example.helloworld package and the HelloWorld class.
Together with the file, IntelliJ IDEA has automatically generated some contents for your class. In this case, the IDE has inserted the package statement and the class declaration.
This is done by means of file templates. Depending on the type of the file that you create, the IDE inserts initial code and formatting that is expected to be in all files of that type. For more information on how to use and configure templates, refer to File templates.
The Project tool window Alt+1 displays the structure of your application and helps you browse the project.
In Java, there’s a naming convention that you should follow when you name packages and classes.
Write the code
Add the main() method using live templates
Type main and select the template that inserts the main() method declaration.
Live templates are code snippets that you can insert into your code. main is one of such snippets. Usually, live templates contain blocks of code that you use most often. Using them can save you some time as you don’t have to type the same code over and over again.
For more information on where to find predefined live templates and how to create your own, refer to Live templates.
Call the println() method using code completion
After the main() method declaration, IntelliJ IDEA automatically places the caret at the next line. Let’s call a method that prints some text to the standard system output.
Type Sy and select the System class from the list of code completion suggestions (it’s from the standard java.lang package).
Press Ctrl+. to insert the selection with a trailing comma.
IntelliJ IDEA shows you the types of parameters that can be used in the current context. This information is for your reference.
For information on different completion modes, refer to Code completion.
Call the println() method using a live template
You can call the println() method much quicker using the sout live template.
After the main() method declaration, IntelliJ IDEA automatically places the caret at the next line. Let’s call a method that prints some text to the standard system output.
Build and run the application
Valid Java classes can be compiled into bytecode. You can compile and run classes with the main() method right from the editor using the green arrow icon in the gutter.
Click in the gutter and select Run ‘HelloWorld.main()’ in the popup. The IDE starts compiling your code.
When the compilation is complete, the Run tool window opens at the bottom of the screen.
If your code is not correct, and the IDE can’t compile it, the Run tool window will display the corresponding exit code.
Once javac finishes compilation, it places the compiled bytecode to the out directory, which is highlighted with yellow in the Project tool window.
After that, the JVM runs the bytecode.
Automatically created run configurations are temporary, but you can modify and save them.
IntelliJ IDEA automatically analyzes the file that is currently opened in the editor and searches for different types of problems: from syntax errors to typos. The Inspections widget at the top-right corner of the editor allows you to quickly see all the detected problems and look at each problem in detail. For more information, refer to Current file.
Package the application in a JAR
Create an artifact configuration for the JAR
To the right of the Main Class field, click and select HelloWorld (com.example.helloworld) in the dialog that opens.
IntelliJ IDEA creates the artifact configuration and shows its settings in the right-hand part of the Project Structure dialog.
Apply the changes and close the dialog.
Build the JAR artifact
If you now look at the out/artifacts folder, you’ll find your JAR there.
Run the packaged application
To make sure that the JAR artifact is created correctly, you can run it.
Use Find Action Ctrl+Shift+A to search for actions and settings across the entire IDE.
Create a run configuration for the packaged application
To run a Java application packaged in a JAR, IntelliJ IDEA allows you to create a dedicated run configuration.
In the Path to JAR field, click and specify the path to the JAR file on your computer.
Doing this means that the HelloWorld.jar is built automatically every time you execute this run configuration.
Run configurations allow you to define how you want to run your application, with which arguments and options. You can have multiple run configurations for the same application, each with its own settings.
Execute the run configuration
On the toolbar, select the HelloWorldJar configuration and click to the right of the run configuration selector. Alternatively, press Shift+F10 if you prefer shortcuts.
As before, the Run tool window opens and shows you the application output.
The process has exited successfully, which means that the application is packaged correctly.
Compile and build applications with IntelliJ IDEA
The IntelliJ IDEA compilation and building process compiles source files and brings together external libraries, properties files, and configurations to produce a living application. IntelliJ IDEA uses a compiler that works according to the Java specification.
You can compile a single file, use the incremental build for a module or a project, and rebuild a project from scratch.
If you have a pure Java or a Kotlin project we recommend that you use IntelliJ IDEA to build your project since IntelliJ IDEA supports the incremental build which significantly speeds up the building process.
However, IntelliJ IDEA native builder might not correctly build the Gradle or Maven project if its build script file uses custom plugins or tasks. In this case, the build delegation to Gradle or Maven can help you build your project correctly.
Compile a single file or class
Open the needed file in the editor and from the main menu, select Build | Recompile ‘class name’ ( Ctrl+Shift+F9 ).
If errors occur during the compilation process, IntelliJ IDEA will display them in the Review compilation and build output along with warning messages.
Change the compilation output locations
Inside the output directory, IntelliJ IDEA also creates subdirectories for each of your modules.
The default paths for subdirectories are as follows:
At the project level, you can change the
/out part of the output path. If you do so (say, specify some instead of
At the module level, you can specify any desirable compilation output location for the module sources and tests individually.
Specify compilation output folders
Open the Project Structure dialog ( File | Project Structure Ctrl+Alt+Shift+S ).
Build
When you execute the Build command, IntelliJ IDEA compiles all the classes inside your build target and places them inside the output directory.
When you change any class inside the build target and then execute the build action, IntelliJ IDEA performs the incremental build that compiles only the changed classes. IntelliJ IDEA also recursively builds the classes’ dependencies.
Build a module, or a project
Select a module or a project you want to compile and from the main menu, select Build | Build Project ( Ctrl+F9 ).
IntelliJ IDEA displays the compilation results in the Review compilation and build output.
If you add a module dependency to your primary module and build the module, IntelliJ IDEA builds the dependent module as well and displays it in the output directory alongside the primary one. If the dependent module has its own module dependencies, then IntelliJ IDEA compiles all of them recursively starting with the least dependent module.
The way the module dependencies are ordered may be very important for the compilation to succeed. If any two JAR files contain classes with the same name, the IntelliJ IDEA compiler will use the classes from the first JAR file it locates in the classpath.
For more information, see Module dependencies.
Rebuild
When you execute a rebuild command, IntelliJ IDEA cleans out the entire output directory, deletes the build caches and builds a project, or a module from scratch. It might be helpful, when the classpath entries have changed. For example, SDKs or libraries that the project uses are added, removed or altered.
Rebuild a module, or a project
From the main menu, select Build | Rebuild Project for the entire project or Build | Rebuild ‘module name’ for the module rebuild.
IntelliJ IDEA displays the build results in the Review compilation and build output.
When the Rebuild Project action is delegated to Gradle or Maven, IntelliJ IDEA doesn’t include the clean task/goal when rebuilding a project. If you need, you can execute the clean command before the rebuild using the Execute Before Rebuild option in the Gradle or Maven tool window.
Background compilation (auto-build)
You can configure IntelliJ IDEA to build your project automatically, every time you make changes to it. The results of the background compilation are displayed in the Problems tool window.
Configure the background compilation
Now when you make changes in the class files, IntelliJ IDEA automatically performs the incremental build of the project.
The automatic build also gets triggered when you save the file ( Ctrl+S ) or when you have the Save files automatically if application is idle for N sec. option selected in the System settings dialog.
Enabling the Build project automatically option also enables Build project in Settings/Preferences | Tools | Actions on Save
When you have the Power Save Mode option ( File | Power Save Mode ) enabled in your project, the auto-build action is disabled, and you need to manually run the build ( Ctrl+F9 ).
Compile before running
By default, when you run an application, IntelliJ IDEA compiles the module where the classes you are trying to run are located.
If you want to change that behavior, you can do so in the Run/Debug Configurations dialog.
Configure a run/debug configuration
In the dialog that opens, create a new or open an existing run configuration.
Click the Modify options link.
If you need to add a new configuration action, click and from the list that opens, select the desired option.
For example, if you select Build Project then IntelliJ IDEA will build the whole project before the run. In this case, the dependencies that were not included in the build with the Build action, will be accounted for. If you select the Build, no error check option, IntelliJ IDEA will run the application even if there are errors in the compilation results.
Review compilation and build output
IntelliJ IDEA reports compilation and building results in the Build tool window, which displays messages about errors and warnings as well as successful steps of compilation.
If you configured an auto-build, then IntelliJ IDEA uses the Problems tool window for messages. The window is available even if the build was executed successfully. To open it, click Auto-build on the status bar.
Double-click a message to jump to the problem in the source code. If you need to adjust the compiler settings, click .
Package an application into a JAR
Create an artifact configuration for the JAR
To the right of the Main Class field, click and select the main class in the dialog that opens (for example, HelloWorld (com.example.helloworld) ).
IntelliJ IDEA creates the artifact configuration and shows its settings in the right-hand part of the Project Structure dialog.
Apply the changes and close the dialog.
Build the JAR artifact
When you’re building a project, resources stored in the Resources root are copied into the compilation output folder by default. If necessary, you can specify another directory within the output folder to place resources.
Run a packaged JAR
To run a Java application packaged in a JAR, IntelliJ IDEA allows you to create a dedicated run configuration.
If you have a Gradle project, use Gradle to create and run the JAR file.
For Maven projects, you can use IntelliJ IDEA to run the JAR file. If you have a Spring Boot Maven project, refer to the Spring section.
Create a run configuration
Add a name for the new configuration.
In the Path to JAR field, click and specify the path to the JAR file on your computer.
Doing this means that the JAR is built automatically every time you execute the run configuration.
Run configurations allow you to define how you want to run your application, with which arguments and options. You can have multiple run configurations for the same application, each with its own settings.
Execute the run configuration
On the toolbar, select the created configuration and click to the right of the run configuration selector. Alternatively, press Shift+F10 if you prefer shortcuts.
As before, the Run tool window opens and shows you the application output.
If the process has exited successfully, then the application is packaged correctly.
Packaging the Application
We can package the application into a Java ARchive file (JAR).
When the code is ready, we can package our application in a JAR. JAR files are often used to deploy an application to the production server. Once a JAR file has been built, it is called an artifact. Let’s take look at how to create artifacts in IntelliJ IDEA.
Creating an Artifact
1) Press Cmd+; on macOS, or Shift+Control+Alt+S on Windows to bring up the Project Structure dialog.
2) Select Artifacts from the left-hand menu and then press the + icon. Select JAR and then From modules with dependencies.
You don’t need to change anything for the Module, however you do need to say which class in your project has the main method. Click the browse button to navigate to your main method. IntelliJ IDEA will show you a list of classes in your project, you only have one so select that.
3) Press OK to select your class. All the other defaults are fine for this tutorial, press OK. Now you can see your new JAR file defined in the Project Structure dialog.
4) If it matches the above screenshot, press OK. You have now defined how to build the JAR file, but you haven’t actually built it yet. You need to build it with your build artifacts.
5) Go to Build > Build Artifacts. You will only have one to choose from which is the one that we just defined.
6) Press Enter to build the artifact. Your status bar at the bottom-left of the screen will show you when this has completed.
To make sure that this JAR file was created correctly you will want to run it. We’ll do this in the next step of this tutorial by using a run configuration.
How to build jars from IntelliJ properly?
I have a project that contains a single module, and some dependencies. I’d like to create a jar, in a separate directory, that contains the compiled module. In addition, I’d like to have the dependencies present beside my module.
No matter how I twist IntelliJ’s «build jar» process, the output of my module appears empty (besides a META-INF file).
23 Answers 23
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Select a Main Class (the one with main() method) if you need to make the jar runnable.
The above sets the «skeleton» to where the jar will be saved to. To actually build and save it do the following:
Extract to the target Jar
Build | Build Artifact | Build
ProjectName | out | artifacts | ProjectName_jar | ProjectName.jar
This is still an issue in 2017, I hope it will help somebody out there! I found 2 possibilities to create working jar-s under IntelliJ 2017.2
1. Creating artifact from IntelliJ:
You have to change manifest directory:
replace «java» with «resources»
This is how it should look like:
Then you choose the dependencies what you want to be packed IN your jar, or NEAR your jar file
To build your artifact go to build artifacts and choose «rebuild». It will create an «out» folder with your jar file and its dependencies.
2. Using maven-assembly-plugin
Add build section to the pom file
This procedure will create the jar file under the «target» folder
I recently had this problem and think these steps are easy to follow if any prior solution or link is missing detail.
For those that benefit from images as I do:
Here are 2 examples with maven project, step by step:
Method 1: Build jar with maven and pom.xml
at pom.xml, add maven-jar-plugin.
screen capture: 4. open maven project box by click on the search icon and type maven,
click on clean, then click on install
your jar file will show up inside the target folder
Method 2: Build jar with maven without pom.xml change
Very important!
The MANIFEST.MF needs to be in your resources folder and the Main.Class needs to refer to
When i use these solution this error coming:
no main manifest attribute, in xxxxx.jar
and solution is:
You have to change manifest directory:
change java to resources
I was trying to build a jar from a multi-module Kotlin app and was getting the notorious ‘no main manifest attribute’ error. Creating the manifest directory in src/main/resources didn’t work either.
As the people above says, but I have to note one point. You have to check the checkbox:
With Maven you can use this plugin:
Jar is ok, since there is compiled output in ‘output’ directory (project/out/production//)
I guess, you have to run ‘make’ before building jar
for dependencies just check «show library» and choose what you want.
Here is the official answer of IntelliJ IDEA 2018.3 Help. I tried and It worked.
To build a JAR file from a module;
On the main menu, choose Build | Build Artifact.
From the drop-down list, select the desired artifact of the type JAR. The list shows all the artifacts configured for the current project. To have all the configured artifacts built, choose the Build all artifacts option.
This solution worked for me (special thanks to Thilina Ashen Gamage (see above) for tip):
Создаем исполняемый jar в Intellij IDEA
IntelliJ IDEA дает возможность быстро создавать исполняемый JAR-файл вашей программы, содержащий модули со всеми зависимостями.
Смотрим видео-инструкцию или следуем пунктам ниже:
Для того, чтобы создать JAR, необходимо проделать всего 3 пункта:
1. Нажмите кнопку ‘+’ в диалоговом окне Project Structure и выберите соответствующий пункт (Рисунок 1):
2. Далее IntelliJ IDEA показывает диалог, позволяющий настроить новый артефакт (Рисунок 2):
Здесь нужно выбрать главный класс вашего проекта и нажать ОK
Рисунок 2 — Диалог создания нового артефакта JAR
Рисунок 3 — Месторасположение сгенерированного JAR файла
Все, теперь исполняемый файл можно запускать.