简体   繁体   English

Visual Studio Code,Java 扩展,如何将 JAR 添加到类路径?

[英]Visual Studio Code, Java Extension, how to add a JAR to classpath?

In Eclipse IDE, I add a JAR library using在 Eclipse IDE 中,我添加了一个 JAR 库,使用

Project > Build Path > Configure Build Path...项目 > 构建路径 > 配置构建路径...

What is the equivalent in VisualStudioCode? VisualStudioCode 中的等价物是什么?

I had a look into launch.json .我查看了launch.json There is a classpath defined.定义了一个类路径。 Adding JARs to this classpath (array) variable seems to have no effect.将 JARs 添加到这个类路径(数组)变量似乎没有效果。

Essentially, this is a duplicate question of Visual Studio Java Language Support add jar .本质上,这是Visual Studio Java Language Support add jar的重复问题。
But that question is unanswered.但这个问题没有答案。

This is such an extremely basic question, that I really don't understand not to find a solution for it in Microsoft's documentation or via Google search.这是一个非常基本的问题,我真的不明白要在 Microsoft 的文档中或通过 Google 搜索找到解决方案。

Update for latest version更新到最新版本

Pre-requisite: In VS Code you need to open the folder and not just file to include any jar file for compilation, running, debugging and testing先决条件:在 VS Code 中,您需要打开文件夹而不仅仅是文件以包含任何用于编译、运行、调试和测试的 jar 文件

VSCode works fine with maven or gradle, and if we are using any of those, we should use maven or gradle for dependency management. VSCode 可以很好地与 maven 或 gradle 配合使用,如果我们使用其中任何一个,我们应该使用 maven 或 gradle 进行依赖管理。

If you are not using any dependency management, then there are two options to add jar file如果你没有使用任何依赖管理,那么有两个选项可以添加 jar 文件

Option 1: Manually选项 1:手动

Open .vscode/settings.json file (if not present, you can create one) and add required jar file there as shown below.打开 .vscode/settings.json 文件(如果不存在,您可以创建一个)并在其中添加所需的 jar 文件,如下所示。 In this case all the jar files present in lib directory will be included + I have added common-logging-1.1.1.jar which is located outside the project directory在这种情况下,将包含 lib 目录中存在的所有 jar 文件 + 我添加了位于项目目录之外的 common-logging-1.1.1.jar

{
    "java.project.referencedLibraries": [
        "lib/**/*.jar",
        "c:\\path\\to\\jarfile\\commons-logging-1.1.1.jar"
    ]
}

Option 2: Via User Interface选项 2:通过用户界面

If Java Extension is enabled then on left panel there will be Java Dependencies.如果启用了 Java 扩展,那么在左侧面板上将会有 Java 依赖项。 Inside there you can click on + symbol to add customer jar files.在那里,您可以单击+符号添加客户 jar 文件。 With this method too, the settings.json file will be updated使用这种方法, settings.json文件也会被更新

添加 Java 依赖项的屏幕截图

Old Answer kept for reference...旧答案留作参考...

VSCode works fine with maven or gradle. VSCode 在 maven 或 gradle 上运行良好。 But without those, as far as I know they have not provided any direct way to add jar file in classpath.但是没有这些,据我所知,他们没有提供任何直接的方法来在类路径中添加 jar 文件。

The workaround is to add the entry in .classpath file manually.解决方法是手动在.classpath文件中添加条目。

For eg in below file I have added common-logging-1.2.jar located in lib directory manually by adding a line <classpathentry exported="true" kind="lib" path="lib/commons-logging-1.2.jar"/>例如,在下面的文件中,我通过添加一行<classpathentry exported="true" kind="lib" path="lib/commons-logging-1.2.jar"/>手动添加了位于lib目录中common-logging-1.2.jar -1.2.jar <classpathentry exported="true" kind="lib" path="lib/commons-logging-1.2.jar"/>

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
        <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
        <classpathentry kind="src" path="src"/>
        <classpathentry kind="output" path="bin"/>
        <classpathentry exported="true" kind="lib" path="lib/commons-logging-1.2.jar"/>
</classpath>

Update更新

Finally VSCode team is working towards a better solution.最后,VSCode 团队正在努力寻找更好的解决方案。 This is still work in progress, but you can refer to this link for better aproach https://github.com/microsoft/vscode-java-pack/issues/94#issuecomment-573487982这仍在进行中,但您可以参考此链接以获得更好的方法https://github.com/microsoft/vscode-java-pack/issues/94#issuecomment-573487982

Update April 2020 2020 年 4 月更新

VSCode Extension update now supports this feature out of the box. VSCode 扩展更新现在支持此功能开箱即用。 Now VS Code Java lets you work with JAR files directly without any build tools.现在 VS Code Java 让您无需任何构建工具即可直接使用 JAR 文件。 Go to JAVA DEPENDENCIES view, find the Referenced Libraries node and click the + icon.转到 JAVA DEPENDENCIES 视图,找到 Referenced Libraries 节点并单击 + 图标。

Reference https://github.com/microsoft/vscode-java-pack/blob/master/release-notes/v0.9.0.md#work-with-jar-files-directly参考https://github.com/microsoft/vscode-java-pack/blob/master/release-notes/v0.9.0.md#work-with-jar-files-directly

I know this is pretty old, but it is still high up on Google results and many may find it.我知道这已经很老了,但它在谷歌搜索结果中仍然很高,很多人可能会发现它。 I just want to recommend the following guide to VSCode wich includes a small but sufficient part to including libraries:我只想推荐以下 VSCode 指南,其中包含一小部分但足够包含库的部分:

https://blog.usejournal.com/visual-studio-code-for-java-the-ultimate-guide-2019-8de7d2b59902 https://blog.usejournal.com/visual-studio-code-for-java-the-ultimate-guide-2019-8de7d2b59902

the answer is pretty simple:答案很简单:

  1. add the jar to a folder you prefer, eg a new directory "lib" in the project folder.将 jar 添加到您喜欢的文件夹中,例如项目文件夹中的新目录“lib”。
  2. add a line like: <classpathentry kind="lib" path="lib/javaxt-cor.jar"/> to your .classpath .添加一行: <classpathentry kind="lib" path="lib/javaxt-cor.jar"/>到您的.classpath
  3. done.完毕。 You can simply import it as you are used to.您可以按照习惯简单地导入它。

import external jar file into java project,now in vscode 1.48.2 is work well,follow the reference below: https://code.visualstudio.com/docs/java/java-project#_working-with-jar-files将外部 jar 文件导入 java 项目,现在在 vscode 1.48.2 中运行良好,请遵循以下参考: https ://code.visualstudio.com/docs/java/java-project#_working-with-jar-files

what I want to said is, if your external jar path has Chinese characters,even if put the jar files into lib directory under project root directory and the project path has chinese characters,when you debug or run,it will report an error message like this:我想说的是,如果你的外部jar路径有中文,即使将jar文件放到项目根目录下的lib目录下,并且项目路径有中文,当你调试或运行时,也会报错这个:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils

I had not idea whether this problem appear in other language characters.be careful.我不知道这个问题是否出现在其他语言字符中。小心。

You must have the Java Dependency Viewer extension installed which helps import the jar files and add them to the project's classpath OR add the libraries to the " .classpath " file manually by using <classpathentry kind="lib" path="manual\path\entry\jarfile.jar"/> tags within <classpath></classpath> tags for each jar file.您必须安装Java Dependency Viewer扩展,这有助于导入 jar 文件并将它们添加到项目的类路径中,或者使用<classpathentry kind="lib" path="manual\path\entry\jarfile.jar"/>手动将库添加到“ .classpath ”文件中每个 jar 文件的<classpath></classpath>标记中的<classpathentry kind="lib" path="manual\path\entry\jarfile.jar"/>标记。

First what you want to do is know how to create a proper Java "project" in VS Code.首先,您要做的是知道如何在 VS Code 中创建适当的 Java“项目”。

To do that:要做到这一点:

  1. Have a folder opened in VSCode在 VSCode 中打开一个文件夹
  2. Press Ctrl+Shift+P to open the Command PaletteCtrl+Shift+P打开命令面板
  3. Type in Java: Create New Project输入Java: Create New Project
  4. Follow the steps according to your requirements and provide the project name根据您的要求按照步骤操作并提供项目名称

Then : Expand the Java Dependencies section in your Explorer Panel then Expand your "project name".然后:展开资源管理器面板中的Java 依赖项部分,然后展开您的“项目名称”。

  1. When you hover over " Referenced Libraries " you will see the " + " sign.当您将鼠标悬停在“引用的库”上时,您将看到“ + ”号。 Click it.点击它。
  2. It will open the explorer.它将打开资源管理器。 Use it to select all your jar files and click " Select Jar Files " button.使用它来选择所有 jar 文件,然后单击“ Select Jar Files ”按钮。

That's it!!!!而已!!!!

By the way you can see all of this in detail at https://code.visualstudio.com/docs/java/java-project#_working-with-jar-files , it has a clear visual representation of everything related.顺便说一句,您可以在https://code.visualstudio.com/docs/java/java-project#_working-with-jar-files详细查看所有这些内容,它对所有相关内容都有清晰的视觉表示。

Happy Coding!!!快乐编码!!!

A terrible solution, but for me it works.一个糟糕的解决方案,但对我来说它有效。 (Assuming maven is installed). (假设已安装 Maven)。

Locate your maven repository directory, for me it is:找到您的 Maven 存储库目录,对我来说是:

/Users/username/.m2/repository

Then create the path required following the package name.然后在包名后面创建所需的路径。 If you don't know the package name you can rename the .jar to a .zip and extract the content.如果您不知道包名称,您可以将.jar重命名为.zip并提取内容。

Also create a version number, if you don't have one then make one up.还要创建一个版本号,如果你没有,那就补一个。 Here is a example of a structure that I created for byte-buddy-agent since that does not have a maven snippet.这是我为byte-buddy-agent创建的结构示例,因为它没有 maven 片段。

Having done that you edit pom.xml and add something among the lines of:完成后,您编辑pom.xml并在以下行中添加一些内容:

<dependency>
  <groupId>net.bytebuddyagent</groupId>
  <artifactId>byte-buddy-agent</artifactId>
  <version>1.9.8</version>
</dependency>

Save the file, reload the changes, and you should be good to go.保存文件,重新加载更改,您应该一切顺利。 A bunch of files should be created in the directory.应该在目录中创建一堆文件。

在此处输入图像描述

For adding external Jar files whithout maven or gradle .classpath file must be changed for the library.. example对于添加外部 Jar 文件,必须为库更改 maven 或 gradle .classpath 文件.. 示例

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="lib" path="lib/log4j-1.2.6.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>

But one extension conflicts with vscode-java.但是一个扩展与 vscode-java 冲突。 https://marketplace.visualstudio.com/items?itemName=georgewfraser.vscode-javac .Disable it if you've installed to suppress error if you find after changing .classpath file. https://marketplace.visualstudio.com/items?itemName=georgewfraser.vscode-javac 。如果您已安装,请禁用它,以在更改 .classpath 文件后发现错误。 You can check this issue- https://github.com/redhat-developer/vscode-java/issues/956你可以检查这个问题 - https://github.com/redhat-developer/vscode-java/issues/956

It's so easy, anyway:无论如何,这很容易:

  1. Create project with java ctrl+shift+p使用 java ctrl+shift+p创建项目
  2. Add the jar file to your .classpath将 jar 文件添加到您的.classpath
  3. Add on the top of your project package [app];在你的项目包顶部添加 [app]; the name of your package您的包裹名称
  4. We are done, don't forget to refresh it.我们完成了,别忘了刷新它。

I'm going to use the Apache Commons Codec http://commons.apache.org/proper/commons-codec/ as an example and start from scratch.我将以 Apache Commons Codec http://commons.apache.org/proper/commons-codec/为例,从头开始。 I've installed the Visual Studio Code Java Pack Installer https://code.visualstudio.com/docs/languages/java and got a new VSCode window.我已经安装了 Visual Studio Code Java Pack Installer https://code.visualstudio.com/docs/languages/java并获得了一个新的 VSCode 窗口。

  1. Ctrl+Shift+P and type to select Java: Create Java Project Ctrl+Shift+P并键入以选择Java: Create Java Project
  2. Choose a folder for your project and click Select the location为您的项目选择一个文件夹,然后单击Select the location
  3. Give your project a name and press Enter为您的项目命名并按 Enter
  4. Create folder in the project called lib and copy in the commons-codec-1.14 folder from the zip file.在名为 lib 的项目中创建文件夹,并从 zip 文件中复制到 commons-codec-1.14 文件夹中。
  5. Open the .classpath file and add the following line inside the node打开 .classpath 文件并在节点内添加以下行
    <classpathentry kind="lib" path="lib/commons-codec-1.14/commons-codec-1.14.jar"/>
    NB You may need to use the absolute address of the lib file.注意 您可能需要使用 lib 文件的绝对地址。 In my first go the above code worked fine.在我第一次去上面的代码工作正常。 My demo project for this guide only worked with a full path eg我的本指南演示项目仅适用于完整路径,例如
    <classpathentry kind="lib" path="C:/Users/tim/Desktop/JavaExample/JavaExample/lib/commons-codec-1.14/commons-codec-1.14.jar"/>
  6. Open the src\App.java file and add the following line below the package app;打开 src\App.java 文件并在package app; line import org.apache.commons.codec.binary.Base64;import org.apache.commons.codec.binary.Base64;

I was then able to run the following code in App.java然后我能够在 App.java 中运行以下代码

package app;
import org.apache.commons.codec.binary.Base64;


public class App {
    public static void main(String[] args) throws Exception {
        String message = "Hello World";
        System.out.println(message);
        String encodedMessage = Base64.encodeBase64String(message.getBytes());
        System.out.println(encodedMessage);

    }
}

To produce生产

Hello World
SGVsbG8gV29ybGQ=

I didn't read every answer here but none of them seem to align with the interface I am seeing.我没有在这里阅读所有答案,但似乎没有一个与我看到的界面一致。 I poked around and noticed that at the bottom of the left hand pane underneath 'OUTLINE' and 'TIMELINE', there was a 'JAVA PROJECTS' accordion menu.我四处张望,注意到在“OUTLINE”和“TIMELINE”下方左侧窗格的底部,有一个“JAVA PROJECTS”手风琴菜单。 When I hover over it, there's an ellipses which, when clicked, brings up a menu containing the option: 'Configure Classpath'.当我将鼠标悬停在它上面时,有一个省略号,单击该省略号会弹出一个包含选项的菜单:“配置类路径”。 Selecting that brings up a Window and the last section is 'Refenced Libraries' where you can add jars from your filesystem.选择它会打开一个窗口,最后一部分是“参考库”,您可以在其中从文件系统添加 jar。

Follow these steps in vscode (2022)vscode (2022) 中按照以下步骤操作

Make sure Extension Pack for Java is installed确保安装了 Java 的扩展包

Install Extension Pack for Java , you may need to restart the vscode.安装Java 的扩展包,你可能需要重启 vscode。

Project Structure项目结构

Create the following创建以下

.vscode/
 | -- settings.json
bin/
lib/ <-- Add here all the .jar files 
src/ <-- Add here you java source code

So that the project structure should look like this所以项目结构应该是这样的

在此处输入图像描述

Add settings to settings.json将设置添加到settings.json

{
    "java.project.sourcePaths": [
        "src"
    ],
    "java.project.outputPath": "bin",
    "java.project.referencedLibraries": [
        "lib/**/*.jar",
    ]
}

  • { "java.project.sourcePaths": [ "src" ], "java.project.outputPath": "bin", "java.project.referencedLibraries": [ "lib/**/*.jar", ] } {“java.project.sourcePaths”:[“src”],“java.project.outputPath”:“bin”,“java.project.referencedLibraries”:[“lib/**/*.jar”,]}

  • java.project.sourcePaths : Path of your java source code java.project.sourcePaths :您的 java 源代码的路径

  • java.project.outputPath Binary output java.project.outputPath二进制 output

  • java.project.referencedLibraries : The .jar files java.project.referencedLibraries.jar文件

Now, restart vscode and also if you still have error you many need to Clear file content cache in Visual Studio Code现在,重新启动vscode ,如果您仍然有错误,您需要在 Visual Studio Code 中清除文件内容缓存

Also you should see now the library in the Referenced Libraries list .此外,您现在应该在Referenced Libraries 列表中看到该库。 (Note: this may be updated in future vscode version, like name, position and so on) (注:这可能会在未来的 vscode 版本中更新,如名称、position 等)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM