Classpath java как прописать intellij idea

от admin

Classpath java как прописать intellij idea

JAR is an abbreviation of JAVA Archive. It is used for aggregating multiple files into a single one, and it is present in a ZIP format. It can also be used as an archiving tool but the main intention to use this file for development is that the Java applets and their components(.class files) can be easily downloaded to a client browser in just one single HTTP request, rather than establishing a new connection for just one thing. This will improve the speed with which applets can be loaded onto a web page and starts their work. It also supports compression, which reduces the file size and the download time will be improved.

Methods: JAR file can be added in a classpath in two different ways

  1. Using eclipse or any IDE
  2. Using command line

Method 1 – Using Eclipse IDE

Step 1: Right-Click on your project name

Step 2: Click on Build Path

Step 3: Click on configure build path

Step 4: Click on libraries and click on “Add External JARs”

Step 5: Select the jar file from the folder where you have saved your jar file

Step 6: Click on Apply and Ok.

Method 2 – Using the command line

Command 1: By including JAR name in CLASSPATH environment variable

CLASSPATH environment variable is not case-sensitive. It can be either Classpath or classpath which is similar to PATH environment variable which we can use to locate Java binaries like javaw and java command.

Command 2: By including name of JAR file in -a classpath command-line option

This option is viable when we are passing –classpath option while running our java program like java –classpath $(CLASSPATH) Main. In this case, CLASSPATH shell variable contains the list of Jar file which is required by the application. One of the best advantages of using classpath command-line option is that it allows us to use every application to have its own set of JAR classpath. In other cases, it’s not available to all Java program which runs on the same host.

Command 3: By including the jar name in the Class-Path option in the manifest

When we are running an executable JAR file we always notice that the Class-Path attribute in the file inside the META-INF folder. Therefore, we can say that Class-Path is given the highest priority and it overrides the CLASSPATH environment variable as well as –classpath command-line option. Henceforth, we can deduce that its a good place to include all JAR files required by Java Application.

Command 4: By using Java 6 wildcard option to include multiple JAR

From Java 1.6+ onwards we can use a wildcard for including all jars in a directory to set classpath or else to provide Java program using classpath command-line option. We can illustrate the Java command example to add multiple JAR into classpath using Java 6 wildcard method as follows,

In this method, we include all JAR files inside ‘D:\lib’ directory into the classpath. We must ensure that syntax is correct. Some more important points about using Java 6 wildcard to include multiple JAR in classpath are as follows:

Use * instead of *.jar

Whenever JAR and classfile are present in the same directory then we need to include both of them separately

In Java 6 wildcard which includes all JAR, it will not search for JARs in a subdirectory.

Wildcard is included in all JAR is not honored in the case when we are running Java program with JAR file and having Class-Path attribute in the manifest file. JAR wildcard is honored when we use –cp or –classpath option

Command 5: Adding JAR in ext directory example be it ‘C:\Program Files\Java\jdk1.6.0\jre\lib\ext’

By using the above method we can add multiple JAR in our classpath. JAR from ext directory can be loaded by extension Classloader. It has been given higher priority than application class loader which loads JAR from either CLASSPATH environment variable or else directories specified in –classpath or –cp

Run Debug Configuration: JAR Application

This run/debug configuration enables you to run applications started via java -jar <name>.jar command.

For an example of how to create and run this configuration, refer to Create a run configuration for the packaged application.

Configuration tab

Specify here the filly-qualified path to the required JAR file.

Specify the string to be passed to the VM for launching an application, for example, -mx , -verbose , and so on.

When specifying JVM options, follow these rules:

Use spaces to separate individual options, for example, -client -ea -Xmx1024m .

If an option includes spaces, enclose the spaces or the argument that contains spaces in double quotes, for example, some" "arg or "some arg" .

If an option includes double quotes (as part of the argument), escape the double quotes using backslashes, for example, -Dmy.prop=\"quoted_value\" .

You can pass environment variable values to custom Java properties. For example, if you define a variable MY_ENV_VAR , you can pass it to the foo property as follows:

The -classpath option specified in this field overrides the classpath of the module.

Type a list of arguments to be passed to the program in the format you would use on the command line. Use the same rules as for specifying the VM options.

Specify the working directory to be used for running the application. This directory is the starting point for all relative input and output paths. By default, the field contains the directory where the project file resides. To specify another directory, click and select the directory.

Expand the list to view available path variables that you can use as a path to your working directory.

The list of path variables may vary depending on the enabled plugins.

Create environment variables and specify their values.

Add dependencies with “provided” scope to classpath

Enable this option to add dependencies with the Provided scope to the runtime classpath.

Shorten command line

Select a method that will be used to shorten the command line if the classpath gets too long, or you have many VM arguments that exceed your OS command line length limitation:

none : IntelliJ IDEA will not shorten a long classpath. If the command line exceeds the OS limitation, IntelliJ IDEA will be unable to run your application and will display a message suggesting you to specify the shortening method.

JAR manifest : IntelliJ IDEA will pass a long classpath via a temporary classpath.jar . The original classpath is defined in the manifest file as a class-path attribute in classpath.jar . You will be able to preview the full command line if it was shortened using this method, not just the classpath of the temporary classpath.jar .

classpath file : IntelliJ IDEA will write a long classpath into a text file.

By default, the newest JDK from the module dependencies is used to run the application. If you want to specify an alternative JDK or JRE here, select it from the list.

Search sources using module’s class path

Use the list to choose the required module. This option tells the debugger and the feature Navigate from stack trace , where the source code for the classes from JAR archive should be sought for.

Code Coverage tab

Use this tab to configure code coverage monitoring options.

Choose coverage runner

Select the desired code coverage runner.

By default, IntelliJ IDEA uses its own coverage engine with the Sampling mode. You can also choose JaCoCo for calculating coverage.

Select this option to measure code coverage with minimal slow-down.

Select this option to collect accurate branch coverage. This mode is available for the IntelliJ IDEA code coverage runner only.

Track per test coverage

Select this checkbox to detect lines covered by one test and all tests covering line. If this checkbox is selected, Track per test coveragebecomes available on the toolbar of the coverage statistic popup.

This option is only available for the Tracing mode of code coverage measurement for the testing run/debug configurations.

Packages and classes to record code coverage data

the Add button

Click and select Add Class or Add Package to specify classes and packages to be measured. You can also remove classes and packages from the list by selecting them in the list and clicking the button.

Enable coverage in test folders

If this checkbox is selected, the folders marked as test root_Test.pngare included in the code coverage analysis.

Logs tab

Use this tab to specify which log files generated while running or debugging should be displayed in the console, that is, on the dedicated tabs of the Run or Debug tool window.

Select checkboxes in this column to have the log entries displayed in the corresponding tabs in the Run tool window or Debug tool window.

The read-only fields in this column list the log files to show. The list can contain:

Full paths to specific files.

Ant patterns that define the range of files to be displayed.

Aliases to substitute for full paths or patterns. These aliases are also displayed in the headers of the tabs where the corresponding log files are shown.

If a log entry pattern defines more than one file, the tab header shows the name of the file instead of the log entry alias.

Select this checkbox to have the previous content of the selected log skipped.

Save console output to file

Select this checkbox to save the console output to the specified location. Type the path manually, or click the browse button and point to the desired location in the dialog that opens .

Show console when a message is printed to standard output stream

Select this checkbox to activate the output console and bring it forward if an associated process writes to Standard.out.

Show console when a message is printed to standard error stream

Select this checkbox to activate the output console and bring it forward if an associated process writes to Standard.err.

Click this button to open the Edit Log Files Aliases dialog where you can select a new log entry and specify an alias for it.

Click this button to edit the properties of the selected log file entry in the Edit Log Files Aliases dialog .

Click this button to remove the selected log entry from the list.

Common settings

When you edit a run configuration (but not a run configuration template), you can specify the following options:

Specify a name for the run configuration to quickly identify it among others when editing or running.

Allow multiple instances

Allow running multiple instances of this run configuration in parallel.

By default, it is disabled, and when you start this configuration while another instance is still running, IntelliJ IDEA suggests stopping the running instance and starting another one. This is helpful when a run configuration consumes a lot of resources and there is no good reason to run multiple instances.

Store as project file

Save the file with the run configuration settings to share it with other team members. The default location is .idea/runConfigurations . However, if you do not want to share the .idea directory, you can save the configuration to any other directory within the project.

Читать:
Как скачать файлы с гугл диска на айфон

By default, it is disabled, and IntelliJ IDEA stores run configuration settings in .idea/workspace.xml .

Toolbar

The tree view of run/debug configurations has a toolbar that helps you manage configurations available in your project as well as adjust default configurations templates.

Create a run/debug configuration.

Delete the selected run/debug configuration. Note that you cannot delete default configurations.

Create a copy of the selected run/debug configuration. Note that you create copies of default configurations.

The button is displayed only when you select a temporary configuration. Click this button to save a temporary configuration as permanent.

Move into new folder / Create new folder. You can group run/debug configurations by placing them into folders.

To create a folder, select the configurations within a category, click , and specify the folder name. If only a category is in focus, an empty folder is created.

Then, to move a configuration into a folder, between the folders or out of a folder, use drag or and buttons.

To remove grouping, select a folder and click .

Click this button to sort configurations in the alphabetical order.

Before launch

In this area, you can specify tasks to be performed before starting the selected run/debug configuration. The tasks are performed in the order they appear in the list.

Click this icon to add one of the following available tasks:

Run External tool : select to run an external application. In the dialog that opens, select one or multiple applications you want to run. If it is not defined in IntelliJ IDEA yet, add its definition. For more information, see External tools and External tools settings.

Run Another Configuration : select to execute another run/debug configuration and wait until it finishes before starting the current configuration. If you want to run several configurations in parallel, use a compound run/debug configuration.

Build : select to compile the specified module. The Build Module command will be executed.

If an error occurs during compilation, IntelliJ IDEA won’t attempt to start the run/debug configuration.

Build Project : select to compile the entire project. The Build Project command will be executed.

If an error occurs during compilation, IntelliJ IDEA won’t attempt to start the run/debug configuration.

Build, no error check : the same as the Build option, but IntelliJ IDEA will try to start the run/debug configuration irrespective of the compilation results.

Build Artifacts : select this option to build an artifact or artifacts. In the dialog that opens, select the artifact or artifacts that should be built.

Launch Web Browser : select this option to have a browser started. In the dialog that opens, select the type of the browser and provide the start URL. Also, specify if you want the browser be launched with JavaScript debugger.

Run Ant target : select this option to run an Ant target. In the dialog that opens, select the target to be run.

Run Grunt task : select this option to run a Grunt task.

In the Grunt task dialog that opens, specify the Gruntfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Grunt tool.

Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the grunt-cli package.

Run gulp task : select this option to run a Gulp task.

In the Gulp task dialog that opens, specify the Gulpfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Gulp tool.

Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the gulp package.

Run Maven Goal : select this option to run a Maven goal. In the dialog that opens, select the goal to be run.

Run npm script : select this option to execute an npm script.

In the NPM Script dialog that opens, specify the npm run/debug configuration settings.

If the Check errors checkbox is selected, the compiler will show all the errors and the run configuration will not start.

If the Check errors checkbox is cleared, the compiler will show all the detected errors but the run configuration still will be launched.

Run Remote External Tool : adds a remote SSH external tool.

Disconnect Data Source : select this option if you want to disrupt the connection to a data source before the run/debug configuration is run.

Click this icon to remove the selected task from the list.

Click this icon to edit the selected task. Make the necessary changes in the dialog that opens.

Click these icons to move the selected task one line up or down in the list. The tasks are performed in the order that they appear in the list.

Select this checkbox to show the run/debug configuration settings prior to actually starting the run/debug configuration.

Activate tool window

By default this checkbox is selected and the Run or the Debug tool window opens when you start the run/debug configuration.

Otherwise, if the checkbox is cleared, the tool window is hidden. However, when the configuration is running, you can open the corresponding tool window for it yourself by pressing Alt+4 or Alt+5 .

How to add Resources Folder, Properties at Runtime into IntelliJ classpath? Adding Property files to Classpath

NullPointerException while reading Resource .properties file in Intellij IDE

Getting NullPointerException while reading Resource .properties file in Intellij IDE?

Do you have an issue loading resources files into your Intellij IDE? Having below errors?

  • Error: Could not find or load main class in intelliJ IDE
  • IntelliJ IDEA – getClass().getResource(“…”) return null
  • Unable to find .properties file at runtime
  • Not able to find resource file in classpath?
  • How to add a property file to a project/module at runtime in Intellij IDE?

Today while running tutorial how to read config.properties file in Java at runtime I got below error in IntelliJ IDE. Program runs very well without any issue in Eclipse IDE.

It took me some time to fix this in IntelliJ IDE as I’m new to JetBrain’s IntelliJ ��

Basically IntelliJ was giving me NullPointerException as it was not able to find resource folder at runtime.

Here is a code block.

How to solve java.lang.NullPointerException: inStream parameter is null error?

Step-1.

  • Right click on project
  • Click on Mark Directory as
  • Click on Sources Root

IntelliJ IDE - Mark Project as Source Root - Crunchify Tips

Step-2.

  • Click on File
  • Click on Project Structure … to open settings panel

Step-3.

  • Click on Modules tab
  • As you see there isn’t any resources folder added as Content Root
  • We need to add resources folder into it

IntelliJ Click on Modules Tab and check added resources - Crunchify

Step-4.

  • Make sure to click on resource folder
  • Click on Resources tab after that
  • You will see resources folder added as Resource Folders in right panel

Add resources folder into resources tab - Crunchify

Step-5.

  • Rerun your Java program

ReRun Crunchify Java Program - Crunchify

Step-6.

Observe result and you won’t see NullPointerException any more.

Config.properties file loaded successfully and no NPE in IntelliJ IDE - Crunchify

I hope this simple tips will help you fix NPE and easy for you to add any resources into your Java or J2EE project at runtime without any issue.

Happy coding and keep sharing.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion. ��

Как добавить каталог в путь к классам в профиле запуска приложения в IntelliJ IDEA?

Если я переопределю, используя -cp x: target / classes в настройках виртуальной машины, я получаю следующую ошибку:

Есть идеи, как добавить каталог в путь к классам для моего проекта?

задан 12 мая ’09, 15:05

Мне непонятно, куда вы это пытаетесь добавить. Из командной строки IJ? Или в свойствах проекта? — Heiko Rupp

9 ответы

В Intellij 13 это снова выглядит немного иначе. Вот инструкции для Intellij 13:

  1. щелкните вид проекта или отобразите его, нажав кнопку «1: Проект» на левой границе окна или нажав Alt + 1
  2. найдите свой проект или подмодуль и щелкните по нему, чтобы выделить его, затем нажмите F4 или щелкните правой кнопкой мыши и выберите «Открыть настройки модуля» (в IntelliJ 14 он стал F12)
  3. перейдите на вкладку зависимостей
  4. Нажмите кнопку «+» справа и выберите «Банки или каталоги . »
  5. Найдите свой путь и нажмите ОК
  6. В диалоговом окне «Выбрать категории выбранного файла» выберите Classes (даже если это свойства), нажмите ОК и еще раз ОК
  7. Теперь вы можете запустить свое приложение, и оно будет иметь выбранный путь в пути к классу.

ответ дан 14 мар ’18, в 05:03

Итак, как бы вы создали конфигурации для запуска с двумя разными каталогами, которые должны присутствовать исключительно в одном, но не в другом. В eclipse вы можете добавить / удалить что угодно в конфигурации запуска. Разве IntelliJ не поддерживает это? — Καrτhικ

Совершенно ясно, что вы можете изменить путь к классам запустить конфигурацию изменения модуль путь к классам. Но точный вопрос заключался в том, «как добавить каталог в путь к классам в приложении. профиль запуска«. Так настоящий был дан uaaquarius — Павел Вязанкин

Спасибо ! Это решило мою проблему после долгих поисков! — JonasCz

Шаг 6 мне не подходит. Я использую intellij 14. У меня есть папка lib, в которой находится мой .jar. выбор папки или банки просто проанализирует путь в intellij. все равно не работает — Такеру

@Takeru Ты понял это? — Россамиш

Похоже, что IntelliJ 11 изменил метод, и проверенный ответ больше не работает для меня. Если кто-то еще попадает сюда через поисковую систему, вот как я решил это в IntelliJ 11:

  1. Перейдите в структуру проекта, нажмите «Модули» и выберите свой модуль.
  2. Выберите вкладку «Зависимости».
  3. Нажмите кнопку «+» справа и выберите «Банки или каталоги . »
  4. Добавьте нужный каталог (и) (обратите внимание, что вы можете выбрать несколько) и нажмите OK.
  5. В появившемся диалоговом окне выберите «классы», а НЕ «каталог jar».
  6. Убедитесь, что вы используете этот модуль в своей цели запуска

Обратите внимание, что шаг 5 кажется ключевым отличием. Если вы выберете «каталог jar», он будет выглядеть точно так же в среде IDE, но не будет включать путь во время выполнения. Похоже, что нет никакого способа определить, выбрали ли вы ранее «классы» или «каталог jar» постфактум.

ответ дан 14 мар ’12, в 15:03

Спасибо вам большое за размещение этого. Вы только что сэкономили мне час или около того. — Джон Цзян

У меня та же проблема, что и раньше, с IJ11, и на этот раз я был рад найти ответ. — Сэл

Идеально. Тот же процесс для IJ12. Просматривайте этот пост при попытке разрешить «java.lang.ClassNotFoundException: com / microsoft / jdbc / sqlserver / SQLServerDriver». Это решило проблему с подключением. Спасибо — джкмерфи1

Я не получаю шаг 5 🙁 Диалог просто не появляется. — Чарльз Вуд

@CharlesWood: Когда я хотел выбрать две папки, одна из которых содержит подпапки. Мне пришлось развернуть папку, содержащую подпапки, с помощью маленькой стрелки рядом с именем папки, чтобы появилось диалоговое окно. В противном случае диалог будет пропущен. — Тимо Рейманн

Вы можете попробовать -Xbootclasspath / a: путь опция запуска Java-приложений. По описанию он определяет «разделенный двоеточиями путь к директориям, архивам JAR и ZIP-архивам для добавления к пути к классу начальной загрузки по умолчанию».

Похожие статьи