Главная страница » Как создать jar файл в intellij idea

Как создать jar файл в intellij idea

  • автор:

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

Alternatively, in the Project tool window, right-click the class you need and from the context menu, select Recompile ‘class name’ .

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

When you compile your source code, IntelliJ IDEA automatically creates an output directory that contains compiled .class files.

Compile output directory

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 <ProjectFolder>/out part of the output path. If you do so (say, specify some <OutputFolder> instead of <ProjectFolder>/out ) but don’t redefine the paths at the module level, the compilation results will go to <OutputFolder>/production/<ModuleName> and <OutputFolder>/test/<ModuleName> .

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

In Project Settings , select Project and in the Project compiler output field, specify the corresponding path.

Project Structure dialog / Projects page

For modules, select Modules , the module you need and the Paths tab. Change the location of the output folder under the Compiler output section.

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.

Project Structure dialog / Module page

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

Press Ctrl+Alt+S to open the IDE settings and select Build, Execution, Deployment | Compiler .

On the Compiler page, select Build project automatically .

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

From the main menu, select Run | Edit Configurations .

In the dialog that opens, create a new or open an existing run configuration.

Click the Modify options link.

In the Add Run Options list, under the Before Launch section, select Add before launch task . The list of tasks becomes available and the Build will be selected. Click to disable it.

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.

IntelliJ IDEA build output

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.

Problems tool window

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

When the code is compiled and ready, you can package your application in a Java archive (JAR) to share it with other developers. A built Java archive is called an artifact .

Create an artifact configuration for the JAR

From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and click Artifacts .

Click , point to JAR , and select From modules with dependencies .

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

From the main menu, select Build | Build Artifacts .

Point to the created .jar ( HelloWorld:jar ) and select Build .

If you now look at the out/artifacts folder, you’ll find your .jar file there.

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

Press Ctrl+Shift+A , find and run the Edit Configurations action.

In the Run/Debug Configurations dialog, click and select JAR Application .

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.

Under Before launch , click , select Build Artifacts in the dialog that opens.

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.

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.

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.

If the Welcome screen opens, click New Project .

Otherwise, from the main menu, select File | New Project .

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.

Make sure that Java is selected in Language , and IntelliJ is selected in Build system .

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

Creating the new project and adding the JDK

If you don’t have the necessary JDK on your computer, select Download JDK . In the next dialog, specify the JDK vendor (for example, OpenJDK), version, change the installation path if required, and click Download .

Leave the Add sample code option disabled as we’re going to do everything from scratch in this tutorial. Click Create .

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.

In the Project tool window, right-click the src folder, select New (or press Alt+Insert ), and then select Java Class .

In the Name field, type com.example.helloworld.HelloWorld and click OK .

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

Place the caret at the class declaration string after the opening bracket < and press Shift+Enter .

In contrast to Enter , Shift+Enter starts a new line without breaking the current one.

Type main and select the template that inserts the main() method declaration.

As you type, IntelliJ IDEA suggests various constructs that can be used in the current context. You can see the list of available live templates using Ctrl+J .

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

Type o , select out , and press Ctrl+. again.

Type p , select the println(String x) method, and press Enter .

IntelliJ IDEA shows you the types of parameters that can be used in the current context. This information is for your reference.

Type " . The second quotation mark is inserted automatically, and the caret is placed between the quotation marks. Type Hello, World!

Basic code completion analyses the context around the current caret position and provides suggestions as you type. You can open the completion list manually by pressing Ctrl+Space .

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.

Type sout and press Enter .

Type " . The second quotation mark is inserted automatically, and the caret is placed between the quotation marks. Type Hello, World! .

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.

The first line shows the command that IntelliJ IDEA used to run the compiled class. The second line shows the program output: Hello, World! . And the last line shows the exit code 0 , which indicates that it exited successfully.

If your code is not correct, and the IDE can’t compile it, the Run tool window will display the corresponding exit code.

When you click Run , IntelliJ IDEA creates a special run configuration that performs a series of actions. First, it builds your application. On this stage, javac compiles your source code into JVM bytecode.

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.

If you want to reopen the Run tool window, press Alt+4 .

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

When the code is ready, you can package your application in a Java archive (JAR) so that you can share it with other developers. A built Java archive is called an artifact .

Create an artifact configuration for the JAR

From the main menu, select File | Project Structure ( Ctrl+Alt+Shift+S ) and click Artifacts .

Click , point to JAR and select From modules with dependencies .

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

From the main menu, select Build | Build Artifacts .

Point to HelloWorld:jar and select Build .

Building an 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.

Press Ctrl+Shift+A , find and run the Edit Configurations action.

In the Run/Debug Configurations dialog, click and select JAR Application .

Name the new configuration: HelloWorldJar .

In the Path to JAR field, click and specify the path to the JAR file on your computer.

Scroll down the dialog and under Before launch , click , select Build Artifacts | HelloWorld:jar .

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.

How to create a JAR file with Maven in IntelliJ

Use Maven to compile and package your Java application

Updated: 10 May 2022

Building a JAR file is the most common way to share your compiled Java application. When you pull dependencies from Maven, they’re actually contained in a bunch of JAR files. So how do you create your own JAR?

Perhaps you’re new to Java development (welcome!), or you’re moving to IntelliJ from Eclipse? Well, fortunately it’s quite easy to create a JAR file in IntelliJ IDEA with a Maven project.

Let’s see how to do it.

Summary

To create a JAR file from a Maven project in IntelliJ IDEA, go to the Maven Tool Window (View → Tool Windows → Maven), expand your project in the tree, expand Lifecycle, and then double-click on package.

Create a JAR of a Maven project

Maven is a project management tool for Java projects, used by lots of projects. Maven can download dependencies, run tests, compile your Java application and package it.

IntelliJ comes with its own Maven instance, which we can control from the IntelliJ GUI.

So whenever we want to perform Maven tasks – like compiling, running tests or packaging – we can use the tools in IntelliJ to do it.

In Maven, all of the tasks to create a JAR are defined in a phase called package . (A phase is just a stage in a build — there are other phases like compile and test .)

An example Maven project

The steps below should work with any basic Maven project, but in case you want to see an example, check out this repository:

Here’s the POM file that I used:

Now let’s create a JAR file from this Maven project.

Create a JAR from your Maven project

Open your Maven project in IntelliJ IDEA (File → Open).

Make sure that the Maven tool window is visible by going to View → Tool Windows → Maven.

Expand your project in the tree, expand Lifecycle and double-click on package.

IntelliJ will run the Maven package phase, and you’ll see the output in another window below.

What is a JAR file, anyway?

A JAR file is kinda special. As well as your compiled classes, it also contains a manifest file ( MANIFEST.MF ).

This manifest file contains some basic info about your app, but it can also contain information about other files inside the JAR.

So it’s better to use your IDE or build tool (like Maven) to help you create it.

Wrapping up

We’ve seen how to create a JAR file for a Maven project in IntelliJ.

By Tom Donohue, Editor | Twitter | LinkedIn

Tom is the founder of Tutorial Works. He’s an engineer and open source advocate. He uses the blog as a vehicle for sharing tutorials, writing about technology and talking about himself in the third person. His very first computer was an Acorn Electron.

Thanks for reading. Let’s stay in touch.

It took us this long to find each other. So before you close your browser and forget all about this article, shall we stay in touch?

Join our free members’ newsletter. We’ll email you our latest tutorials and guides, so you can read at your leisure! �� (No spam, unsubscribe whenever you want.)

Thank you!

We’ve sent you an email. Please check your email, and click the link inside to confirm your subscription.

Want more? Read these articles next.

How to find out where a Maven dependency comes from: Need to know exactly which libraries and dependencies your Java project is using? Maven knows that. Here’s how find out.

Run a web server in a Linux VM with Vagrant [Learning Project]: Learn Linux and virtualisation basics by deploying a website in this tutorial.

How to create a simple HTTP server in Java with Undertow: Create a very lightweight Java web server, which packages to a small fat-jar, under 3MB; ideal for learning or demos

Java IDEs: The Definitive Guide (and Top Picks): Not all IDEs are created the same, so if you’re writing Java code, make sure you choose a good one.

You might also like.

Advertisements report this ad Advertisements

Tutorial Works is a website to help you navigate the world of IT, and grow your tech career, with tips, tutorials, guides, and real opinions.

Thanks for being here today! ��

Copyright © 2022 Tom Donohue. All rights reserved, except where stated. You can use our illustrations on your own blog, as long as you include a link back to us.

intellij-idea Exporting Building a .jar

Eventually, when you’re ready to release a version of your code to production, you’ll need a .jar file to distribute. Intellij makes building JARs quite easy.

First, navigate to File -> Project Structure and click on Artifacts : Artifacts

Click on the + button, and select JAR -> From modules with dependencies : enter image description here

Select your module from the dropdown list, and the main file (this is the file that contains your public static void main() method): enter image description here

Click OK , verify that all the information regarding dependencies is correct, and click OK to finish setting up the artifact. enter image description here

We’re not done yet! We’ve only told Intellij how to build the artifact, now we actually need to make the .jar .

Simply click Build -> Build Artifacts , and click Build on the popup menu: enter image description here

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *