Visual studio code java настройка
This tutorial shows you how to write and run Hello World program in Java with Visual Studio Code. It also covers a few advanced features, which you can explore by reading other documents in this section.
For an overview of the features available for Java in VS Code, see Java Language Overview.
If you run into any issues when following this tutorial, you can contact us by entering an issue.
Setting up VS Code for Java development
Coding Pack for Java
To help you set up quickly, you can install the Coding Pack for Java, which includes VS Code, the Java Development Kit (JDK), and essential Java extensions. The Coding Pack can be used as a clean installation, or to update or repair an existing development environment.
Note: The Coding Pack for Java is only available for Windows and macOS. For other operating systems, you will need to manually install a JDK, VS Code, and Java extensions.
Installing extensions
If you are an existing VS Code user, you can also add Java support by installing the Extension Pack for Java, which includes these extensions:
The Extension Pack for Java provides a Quick Start guide and tips for code editing and debugging. It also has a FAQ that answers some frequently asked questions. Use the command Java: Tips for Beginners from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) to launch the guide.
You can also install extensions separately. The Extensions Guide is provided to help you. You can launch the guide with the Java: Extensions Guide command.
Installing and setting up a Java Development Kit (JDK)
To use Java within Visual Studio Code, you need to install a Java Development Kit (JDK) on your local environment. JDK is a software development environment used for developing Java applications.
Supported Java versions
The Extension Pack for Java supports Java version 1.5 or above.
Note: To configure JDKs for your projects, see Configure Runtime for Projects. To enable Java preview features, see How can I use VS Code with new Java versions.
Installing a Java Development Kit (JDK)
If you have never installed a JDK before and need to install one, we recommend you to choose from one of these sources:
Creating a source code file
Create a folder for your Java program and open the folder with VS Code. Then in VS Code, create a new file and save it with the name Hello.java . When you open that file, the Java Language Server automatically starts loading, and you should see a language status item with a loading icon on the right side of the Status Bar showing the language status is busy. After it finishes loading, you can hover on the language status item and find the loading process has been finished successfully. You can also choose to pin the status item in the status bar.
Note: If you open a Java file in VS Code without opening its folder, the Java Language Server might not work properly.
VS Code will also try to figure out the correct package for the new type and fill the new file from a template. See Create new file.
You can also create a Java project using the Java: Create Java Project command. Bring up the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and then type java to search for this command. After selecting the command, you will be prompted for the location and name of the project. You can also choose your build tool from this command.
Visual Studio Code also supports more complex Java projects — see Project Management.
Editing source code
You can use code snippets to scaffold your classes and methods. VS Code also provides IntelliSense for code completion, and various refactor methods.
To learn more about editing Java, see Java Editing.
Running and debugging your program
To run and debug Java code, set a breakpoint, then either press F5 on your keyboard or use the Run > Start Debugging menu item. You can also use the Run|Debug CodeLens option in the editor. After the code compiles, you can see all your variables and threads in the Run view.
The debugger also supports advanced features such as Hot Code Replace and conditional breakpoints.
For more information, see Java Debugging.
More features
The editor also has many more capabilities to assist with your Java workload.
Support for Java in Visual Studio Code is provided through a wide range of extensions. Combined with the power of core VS Code, these extensions give you a lightweight and performant code editor that also supports many of the most common Java development techniques.
This article will give you an overview of different capabilities of Visual Studio Code for Java developers. For a quick walkthrough of editing, running, and debugging a Java program with Visual Studio Code, use the Java Getting Started Tutorial button below.
Overview
VS Code provides essential language features such as code completion, refactoring, linting, formatting, and code snippets along with convenient debugging and unit test support. VS Code also integrates with tooling and frameworks such as Maven, Tomcat, Jetty, and Spring Boot. Leveraging the power of Visual Studio Code, Java developers get an excellent tool for both quick code editing and also the full debugging and testing cycle. It's a great choice for your Java work if you're looking for a tool which:
- Is fast, lightweight, free, and open source.
- Supports many other languages, not just Java.
- Helps start your Java journey without installing and learning a complex IDE.
- Provides great microservices support including popular frameworks, container tooling, and cloud integration.
- Offers team-based collaboration features such as Visual Studio Live Share.
- Improves your productivity through IntelliSense and other code-aware editing features.
Install Visual Studio Code for Java
To help you set up quickly, we recommend you use the Coding Pack for Java, which is the bundle of VS Code, the Java Development Kit (JDK), and a collection of suggested extensions by Microsoft. The Coding Pack can also be used to fix an existing development environment.
Note: The Coding Pack for Java is only available for Windows and macOS. For other operating systems, you will need to manually install a JDK, VS Code, and Java extensions.
If you have already installed VS Code and want to add Java support to it, we recommend using the Extension Pack for Java, a collection of extensions suggested by Microsoft:
Alternatively, you can add Java language support to VS Code by installing the popular Java extensions by yourself.
Download VS Code - If you haven't downloaded VS Code yet, quickly install for your platform (Windows, macOS, Linux).
There are also other popular Java extensions you can pick for your own needs, including:
Thanks to the great Java community around VS Code, the list doesn't end there. You can search for more Java extensions easily within VS Code:
- Go to the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).
- Filter the extensions list by typing "java".
This document describes some of the key features included in those Java extensions.
Getting started
NOTE: If you are using VS Code on Windows and want to take advantage of the Windows Subsystem for Linux, see Developing in WSL.
Install a Java Development Kit (JDK)
A Java Development Kit (JDK) is a software development environment used for developing Java applications. In order to run Java within Visual Studio Code, you need to install a JDK. The Extension Pack for Java supports Java version 1.5 or above.
We recommend you to consider installing the JDK from one of these sources:
Note: If you have multiple JDKs installed and need to use a specific JDK version for your projects, see Configure Runtime for Projects. To enable Java preview features, see How can I use VS Code with new Java versions.
For developers new to Java or new to VS Code, we do provide some tips in our extensions. Once you've installed the Extension Pack for Java, you can see the tips using the Java: Tips for Beginners command from the Command Palette in VS Code Open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and type "Java: Getting Started".
Working with Java source files
You can use VS Code to read, write, run, and debug Java source file(s) without creating a project. VS Code for Java supports two modes, lightweight and standard. Lightweight mode is ideal for scenarios that only deal with source file(s). If you want to work with a full-scale project, standard mode will be required. You can easily switch from lightweight mode to standard mode, when needed. To learn more, see Lightweight Mode.
Working with Java projects
There are three things you must understand to work with Java in VS Code:
- How does VS Code handle Workspaces?
- How does VS Code handle Java?
- How does VS Code handle Workspaces that contain Java?
VS Code Workspaces
In Visual Studio Code, a "Workspace" means a collection of one or more filesystem folders (and their children) and all of the VS Code configurations that take effect when that "Workspace" is open in VS Code. There are two kinds of "Workspaces" in VS Code, "folder workspaces" and "multi-root workspaces".
A "folder workspace" is presented by VS Code when you open a filesystem folder (directory) in VS Code.
A "multi-root workspace" can refer to multiple folders (directories) from disparate parts of the file system and VS Code displays the contents of the folder(s) of the workspace together in the File Explorer. To learn more, see Multi-root Workspaces.
Java projects in VS Code
In contrast to IDEs such as IntelliJ IDEA, NetBeans, or Eclipse, the concept of a "Java project" is provided entirely by extensions, and is not a core concept in the base VS Code. When working with "Java projects" in VS Code, you must have the necessary extensions installed to work with those project files.
For example, Maven, Eclipse, and Gradle Java projects are supported through Language Support for Java™ by Red Hat, by utilizing M2Eclipse, which provides Maven support, and Buildship, which provides Gradle support through the Eclipse JDT Language Server.
With Maven for Java, you can generate projects from Maven Archetypes, browse through all the Maven projects within your workspace, and execute Maven goals easily from an embedded explorer. Projects can also be created and managed with the Project Manager for Java extension.
Visual Studio Code also supports working with standalone Java files outside of a Java project, described in the Getting Started with Java tutorial.
VS Code Workspaces that contain Java projects
Assuming the necessary Java extensions are installed, opening a VS Code workspace that contains Java artifacts will cause those extensions to understand those artifacts and present options for working with them.
More details about Java project support can be found in Java Project Management in Visual Studio Code and Java Build Tools.
Editing
Code Navigation
Java in Visual Studio Code also supports source code navigation features such as search for symbol, Peek Definition, and Go to Definition. The Spring Boot Tools extension provides enhanced navigation and code completion support for Spring Boot projects.
One of the key advantages of VS Code is speed. When you open your Java source file or folder, within a few seconds, with the help of Lightweight Mode, you will be able to navigate your code base with the Outline view, as well as commands such as Go to Definition and Go to Reference. This is especially useful when you open a project for the first time.
Code Completion
IntelliSense is a general term for language features, including intelligent code completion (in-context method and variable suggestions) across all your files and for both built-in and third-party modules. VS Code supports code completion and IntelliSense for Java through Language Support for Java™ by Red Hat. It also provides AI-assisted IntelliSense called IntelliCode by putting what you're most likely to use at the top of your completion list.
For more details, see Java Code Navigation and Editing. VS Code also supports a range of Refactoring and Linting features.
Debugging
Debugger for Java is a lightweight Java Debugger based on Java Debug Server. It works with Language Support for Java™ by Red Hat to allow users to debug Java code within Visual Studio Code.
Starting a debugging session is easy: click the Run|Debug button available at the CodeLens of your main() function, or press F5 . The debugger will automatically generate the proper configuration for you.
Although it's lightweight, the Java debugger supports advanced features such as expression evaluation, conditional breakpoints, and Hot Code Replace. For more debugging-related information, visit Java Debugging.
Testing
With the support from the Test Runner for Java extension, you can easily run, debug, and manage your JUnit and TestNG test cases.
For more about testing, read Testing Java.
Spring Boot, Tomcat, and Jetty
To further improve your Java productivity in VS Code, there are extensions for most popular frameworks and tools, such as Spring Boot, Tomcat, and Jetty, created by the community.
See Application Servers to learn more about support for Tomcat and Jetty, as well as other application servers with VS Code.
Spring Boot support is provided by Pivotal. There are also the Spring Initializr Java Support and Spring Boot Dashboard extensions provided by Microsoft, to further improve your experience with Spring Boot in Visual Studio Code.
See Spring Boot with VS Code to learn more about Spring Boot support in VS Code, and also Deploy to Azure Web Apps or Deploy to Azure Spring Cloud to learn more about deploying Spring apps to Azure from VS Code.
The Project Manager for Java extension helps you to manage your Java projects and their dependencies. It also helps you to create new Java projects, packages, and classes. To get the complete Java language support in Visual Studio Code, you can install the Extension Pack for Java, which includes the Project Manager for Java extension.
For details on how to get started with the extension pack, you can review the Getting Started with Java tutorial.
Projects view
The Java Projects view helps you view your Java projects and their dependencies, and provides entry points for project management tasks.
By default, the Java Projects view is displayed below the Explorer view. If you cannot see it, try clicking the . button in the EXPLORER title bar and select Java Projects.
In the overflow button of the navigation bar, there are more options to use. For example, you can switch between hierarchical view and flat view.
You can find buttons next to the nodes in the Explorer, which provide useful shortcuts for some actions.
There are also many useful features in each node's context menu, you can right-click on the node in Explorer to toggle it out.
Create a new Java project
You can create a new Java project by clicking the + button in the navigation bar, or through the command: Java: Create Java Project. in Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). During creation, VS Code will facilitate installing required extension(s) per your project type, if the extension(s) weren't already installed.
Import Java projects
You can directly import existing Java projects and modules to your workspace through File > Open Folder. (Make sure the opened folder contains your build tool scripts, for example, pom.xml or build.gradle ). VS Code for Java will detect your projects and import them automatically.
When you add a new module into your projects, you can trigger the command Java: Import Java projects in workspace to import them to your workspace. This command helps to import new projects into the workspace without the need to reload the VS Code window.
Export to JAR
You can export your build to JAR from the projects view or by running the command Java: Export Jar. .
Configure Runtime for Projects
Note: You can set one of them to default by adding "default": true to the entry. The default JDK will be used for your unmanaged folders (with out build tools).
To see which JDKs are used for your projects, you can trigger the command Java: Configure Java Runtime in Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). This command opens a view displaying the runtime information for your projects:
Change JDK for Maven and Gradle projects
If you want to change the JDK version for your Maven or Gradle projects, you need to update it in your build scripts ( pom.xml or build.gradle ). You can click to see how to make such changes. Click will navigate to the build script file of the project.
Change JDK for unmanaged folders
To change the JDK for unmanaged folders (with out any build tools), you can click the button. It will list all the JDKs and you can select one for your unmanaged folders.
Download JDKs
If you want to download a new JDK, you can click the download link, or trigger the command Java: Install New JDK in Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). It will open a new view guiding you to download JDKs.
Configure classpath for unmanaged folders
The Project Management for Java extension provides a user interface to configure the classpath for unmanaged folders. The classpath can be set manually in the classpath configuration page. You can open it by executing the Java: Configure Classpath command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
In some rare cases, you may need to clean the Java workspace by executing the Java: Clean Java Language Server Workspace command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) to let the language server rebuild your dependencies.
Dependency management
Add a Maven dependency
For Maven project, you can add a dependency by clicking the + icon next to Maven Dependencies node in project view.
Manage dependencies for unmanaged folder
If your project is an unmanaged folder without any build tools. You can manage the dependencies by clicking the + icon or the - icon on the Referenced Libraries node or the items under it.
You can also manage the dependencies in the classpath configuration page. See: Configure classpath for unmanaged folder
Behind the scene, there's a setting java.project.referencedLibraries in settings.json . Below are details on how to customize this setting.
Include libraries
The libraries to reference are described using a set of glob patterns.
The settings above will add all .jar files in workspace's library folder along with foo.jar from a specified absolute path to the project's external dependencies.
The referenced libraries are then watched by VS Code, and the project will be refreshed if there is a change to any of these dependent files.
By default, VS Code will reference all JAR files in workspace's lib directory using the glob pattern lib/**/*.jar .
Exclude some libraries
If you want to exclude some libraries from the project, you can expand java.project.referencedLibraries to use include/exclude fields and add an exclude glob pattern:
In the example above, any binary JAR files in the library/sources folder are ignored as the project's external dependencies.
Attach source jars
By default, a referenced .jar will try to search -sources.jar under the same directory, and attach it as source if one match is found.
If you want to manually specify a JAR file as a source attachment, you can provide a key-value map in the sources field:
In this way, bar-src.jar is attached to bar.jar as its source.
Lightweight Mode
VS Code for Java supports two modes, lightweight and standard. With lightweight mode, only source files and JDK are resolved by the language server; with standard mode, imported dependencies are resolved and the project is built by the language server. Lightweight mode works best when you need a quick-start and lightweight environment to work with your source files, for example, reading source code, navigating among source code and JDK, viewing outline and Javadoc, and detecting and fixing syntax errors. Also, code completion is supported within the scope of source files and JDK.
Lightweight mode doesn't resolve imported dependencies nor build the project, so it does not support running, debugging, refactoring, linting, or detecting semantic errors. For these features to be available, you need to switch your workspace from lightweight mode to standard mode.
You can control which mode to launch with by configuring java.server.launchMode with the options below:
- Hybrid (default) - Firstly, a workspace is opened with lightweight mode. You will be asked whether to switch to standard mode if your workspace contains unresolved Java projects. If you choose Later, it will stay in lightweight mode. You can click the language status item on the Status bar to manually switch to standard mode.
- Standard - A workspace is opened with standard mode.
- LightWeight - A workspace is opened with lightweight mode. You can click the language status item on the Status bar to manually switch to standard mode.
The language status item indicates which mode the current workspace is in using different icons.
- - workspace opened with lightweight mode.
- - workspace in the process of being opened with standard mode.
- - workspace opened with standard mode.
Clicking the language status item switches to standard mode.
Build Status
When you edit Java source code in Visual Studio Code, the Java language server is building your workspace to provide you with the necessary language features. You can see the detailed build task status and watch what is happening behind the scene by clicking the language status item in the Status bar. You can also select the check details link when a notification shows the language server is opening Java projects to see the build task status.
Additional resources
There are several Visual Studio Code extensions to support different build systems for Java. Below are extensions for several popular build systems.
If you run into any problems when using the features above, you can contact us by filing an issue.
Visual Studio Code allows you to debug Java applications through the Debugger for Java extension. It's a lightweight Java debugger based on Java Debug Server, which extends the Language Support for Java™ by Red Hat.
Here's a list of supported debugging features:
- Launch/Attach
- Breakpoints
- Exceptions
- Pause & Continue
- Step In/Out/Over
- Variables
- Call Stacks
- Threads
- Debug Console
- Evaluation
- Hot Code Replace
The Java debugger is an open-source project, which welcomes contributors to collaborate through GitHub repositories:
If you run into any issues when using the features below, you can contact us by entering an issue.
Install
To get the complete Java language support in Visual Studio Code, you can install the Extension Pack for Java, which includes the Debugger for Java extension.
For details on how to get started with the extension pack, you can review the Getting Started with Java tutorial.
Configure
By default, the debugger will run out-of-box by automatically finding the main class and generating a default launch configuration in memory to launch your application.
If you would like to customize and persist your launch configuration, you can select the create a launch.json file link in the Run and Debug view.
The launch.json file is located in a .vscode folder in your workspace (project root folder).
For more details on how to create the launch.json , read Launch configurations; for more details on configuration options for Java, you can read Configuration options.
Run and Debug
The debugger extension provides multiple ways to run and debug your Java application.
Run from CodeLens
You will find Run|Debug on the CodeLens of your main() function.
Run from Editor menu
Another way to start debugging is to select Run Java or Debug Java menu from the top editor title bar.
Run from pressing F5
Pressing F5 , the debugger will automatically find the entry point of your project and start debugging. You can also start a debugging session from the Run and Debug view from the side bar of VS Code. See more at Debugging in VS Code.
Debugging single files
In addition to support for debugging Java projects managed by build tools, VS Code also supports for debugging single Java files without any project.
Debug session inputs
The default Debug Console in VS Code doesn't support inputs. If your program need inputs from a terminal, you can use the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) within VS Code or an external terminal to launch it. You can also use the user setting java.debug.settings.console to configure a global console for all Java debug sessions.
Breakpoints
The Debugger for Java supports various breakpoints, such as line breakpoints, conditional breakpoints, data breakpoints, logpoints.
Breakpoint - Conditional breakpoint
With the help of expression evaluation, the debugger also supports conditional breakpoint. You can set your breakpoint to break when expression evaluates to true.
Breakpoint - Data breakpoint
You can have the debugger break when a variable changes its value. Note that the data breakpoint can only be set inside a debug session. This means you need to launch your application and break on a regular breakpoint first. You can then pick a field in the VARIABLES view and set a data breakpoint.
Breakpoint - Logpoints
Logpoints is also supported by Java Debugger. Logpoints allow you to send output to Debug Console without editing code. They're different from breakpoints because they don't stop the execution flow of your application.
Expression evaluation
The debugger also lets you evaluate expressions in the WATCH window as well as the Debug Console.
Hot Code Replace
Another advanced feature the debugger supports is 'Hot Code' replacement. Hot Code Replace (HCR) is a debugging technique whereby the Debugger for Java transmits the class changes over the debugging channel to another Java Virtual Machine (JVM). HCR facilitates experimental development and fosters iterative trial-and-error coding. With this new feature, you can start a debugging session and change a Java file in your development environment, and the debugger will replace the code in the running JVM. No restart is required, which is why it's called "hot". Below is an illustration of how you can use HCR with Debugger for Java in VS Code.
- manual - Click the toolbar to apply the changes (default).
- auto - Automatically apply the changes after compilation.
- never - Disable Hot Code Replace.
Step filtering
Step filter is supported by the extension to filter out types that you do not want to see or step through while debugging. With this feature, you can configure the packages to filter within your launch.json so they could be skipped when you step through.
Configuration options
There are many options and settings available to configure the debugger. For example, configuring the JVM arguments and environment variables is easily done with launch options.
Consult the documentation for the Language Support for Java™ by Red Hat extension for help with setting up your project.
For many commonly used setups, there are samples available in VS Code Java Debugger Configuration. The document explains how the Java debugger automatically generates configurations for you, and if you need to modify them, how to do so with Main class, different arguments, environment, attaching to other Java processes, and usage of more advanced features.
Below are all the configurations available for Launch and Attach . For more information about how to write the launch.json file, refer to Debugging.
Launch
- mainClass (required) - The fully qualified class name (for example [java module name/]com.xyz.MainApp) or the java file path of the program entry.
- args - The command-line arguments passed to the program. Use "$" to prompt for program arguments. It accepts a string or an array of string.
- sourcePaths - The extra source directories of the program. The debugger looks for source code from project settings by default. This option allows the debugger to look for source code in extra directories.
- modulePaths - The modulepaths for launching the JVM. If not specified, the debugger will automatically resolve from current project.
- classPaths - The classpaths for launching the JVM. If not specified, the debugger will automatically resolve from current project.
- encoding - The file.encoding setting for the JVM. If not specified, 'UTF-8' will be used. Possible values can be found in Supported Encodings.
- vmArgs - The extra options and system properties for the JVM (for example -Xms -Xmx -D=), it accepts a string or an array of string.
- projectName - The preferred project in which the debugger searches for classes. There could be duplicated class names in different projects. This setting also works when the debugger looks for the specified main class when launching a program. It is required when the workspace has multiple Java projects, otherwise the expression evaluation and conditional breakpoint may not work.
- cwd - The working directory of the program. Defaults to $ .
- env - The extra environment variables for the program.
- envFile - Absolute path to a file containing environment variable definitions.
- stopOnEntry - Automatically pause the program after launching.
- console - The specified console to launch the program. If not specified, use the console specified by the java.debug.settings.console user setting.
- internalConsole - VS Code Debug Console (input stream not supported).
- integratedTerminal - VS Code Integrated Terminal.
- externalTerminal - External terminal that can be configured in user settings.
- none - Launch the program with the standard command line 'java [options] classname [args]'.
- jarmanifest - Generate the classpath parameters to a temporary classpath.jar file, and launch the program with the command line 'java -cp classpath.jar classname [args]'.
- argfile - Generate the classpath parameters to a temporary argument file, and launch the program with the command line 'java @argfile [args]'. This value only applies to Java 9 and higher.
- auto - Automatically detect the command-line length and determine whether to shorten the command line via an appropriate approach.
- classNameFilters - [Deprecated - replaced by skipClasses ] Skip the specified classes when stepping. Class names should be fully qualified. Wildcard is supported.
- skipClasses - Skip the specified classes when stepping. You could use the built-in variables such as '$JDK' and '$Libraries' to skip a group of classes, or add a specific class name expression, for example java.* , *.Foo .
- skipSynthetics - Skip synthetic methods when stepping.
- skipStaticInitializers - Skip static initializer methods when stepping.
- skipConstructors - Skip constructor methods when stepping.
Attach
- hostName (required) - The host name or IP address of remote debuggee.
- port (required) - The debug port of remote debuggee.
- processId - Use process picker to select a process to attach, or Process ID as integer.
- $ - Use process picker to select a process to attach.
- An integer PID - Attach to the specified local process.
- classNameFilters - [Deprecated - replaced by skipClasses ] Skip the specified classes when stepping. Class names should be fully qualified. Wildcard is supported.
- skipClasses - Skip the specified classes when stepping. You could use the built-in variables such as '$JDK' and '$Libraries' to skip a group of classes, or add a specific class name expression, for example java.* , *.Foo .
- skipSynthetics - Skip synthetic methods when stepping.
- skipStaticInitializers - Skip static initializer methods when stepping.
- skipConstructors - Skip constructor methods when stepping.
User settings
- java.debug.logLevel : Minimum level of debugger logs that are sent to VS Code, defaults to warn .
- java.debug.settings.showHex : Show numbers in hex format in Variables, defaults to false .
- java.debug.settings.showStaticVariables : Show static variables in Variables, defaults to false .
- java.debug.settings.showQualifiedNames : Show fully qualified class names in Variables, defaults to false .
- java.debug.settings.showLogicalStructure : Show the logical structure for the Collection and Map classes in Variables, defaults to true .
- java.debug.settings.showToString : Show 'toString()' value for all classes that override 'toString' method in Variables, defaults to true .
- java.debug.settings.maxStringLength : The maximum length of strings displayed in Variables or Debug Console. Strings longer than this limit will be trimmed. The default is 0 , which means no trim is performed.
- java.debug.settings.hotCodeReplace : Reload the changed Java classes during debugging, defaults to manual . Make sure java.autobuild.enabled is not disabled for the Java Language Support extension. See the Hot Code Replace wiki page for more information about usages and limitations.
- manual - Click the toolbar to apply the changes.
- auto - Automatically apply the changes after compilation.
- never - Never apply the changes.
- internalConsole - VS Code Debug Console (input stream not supported).
- integratedTerminal - VS Code Integrated Terminal.
- externalTerminal - External terminal that can be configured in user settings.
Troubleshooting
If you encounter issues when using the debugger, a detailed troubleshooting guide can be found in the vscode-java-debug GitHub repository.
Common issues explained include:
- Java Language Support extension fails to start.
- Build failed, do you want to continue?
- *.java isn't on the classpath. Only syntax errors will be reported.
- Program Error: Could not find or load main class X.
- Program throws ClassNotFoundException.
- Failed to complete Hot Code Replace.
- Please specify the host name and the port of the remote debuggee in the launch.json.
- Failed to evaluate. Reason: Cannot evaluate because the thread is resumed.
- Cannot find a class with the main method.
- No delegateCommandHandler for vscode.java.startDebugSession when starting Debugger.
- Failed to resolve classpath.
- Request type "X" is not supported. Only "launch" and "attach" are supported.
Feedback and questions
You can find the full list of issues at the vscode-java-debug repository. You can submit a bug or feature suggestion and participate in the community driven vscode-java-debug Gitter channel.
Visual Studio Code — популярный редактор кода, бесплатный и с открытым исходным кодом. Но я уверен: каждый из нас, кто пытался настроить Visual Studio Code для разработки приложений на C++, Java или Python, прошел через стадию: “О Боже! Почему нельзя как-нибудь попроще?” Я сам пробовал настроить VS Code пару раз и в итоге закончил тем, что использовал CodeBlocks. :-(
Прочитав много документации, посмотрев ряд роликов на YouTube и потратив несколько дней на саму настройку VS Code, я пишу эту статью, чтобы все это не пришлось проделывать уже вам!
Сегодня я покажу, как настроить среду разработки для спортивного программирования на C++, Java и Python в VS Code с нуля. Мы также посмотрим, какие расширения больше всего пригодятся, чтобы начать работу с VS Code. В конечном счете, ваша среда разработки будет выглядеть примерно так:
Скачайте последнюю версию Visual Studio Code с официального сайта. Рекомендуется загрузить системный установщик (System Installer), но если у вас нет прав администратора, то пользовательский установщик (User Installer) тоже подойдет. Выполните все обычные шаги по установке и обязательно проставьте все следующие чекбоксы:
Если у вас уже установлен VS Code, но вы все равно хотите начать с чистого листа, следуйте этим инструкциям, чтобы полностью удалить VS Code.
Ниже приведен список расширений, которые нам понадобятся для правильной настройки VS Code. Откройте VS Code и перейдите на панель расширений (Ctrl + Shift + X), которая находится на левой панели инструментов, и начните загружать друг за другом следующие расширения:
-
от Microsoft — [Важно] Для корректной работы этого расширения нам понадобится установленный и добавленный в PATH компилятор MinGW. Если у вас его нет, следуйте этому руководству. от austin. от Microsoft — вам нужно будет настроить Python для работы этого расширения. Загрузите и установите последнюю версию отсюда. от Microsoft — [Важно] Перед установкой убедитесь, что в вашей системе настроены Java 8 JDK и JRE и указаны все необходимые переменные среды для Java. Если нет, посмотрите это видео о том, как настроить Java на вашем компьютере. от Jun Han — мы будем использовать это расширение для запуска всех наших программ. Для этого необходимо выполнить некоторые шаги по настройке. Мы увидим эти шаги в следующих разделах.
Расширения, перечисленные ниже, необязательны для дальнейшей настройки, но я рекомендую вам обратить на них внимание, посмотреть, заинтересуют ли они вас, и если нет, то перейти к следующему разделу.
- (Необязательно) Material Theme от Mattia Astronio — это расширение содержит множество приятных глазу тем. Вы можете выбрать любую, какая понравится. Лично я предпочитаю Monokai, которая доступна в VS Code по умолчанию, без каких-либо расширений.
Чтобы выбрать тему, нажмите Ctrl + Shift + P. Откроется палитра команд. Осуществите поиск по слову “theme” и выберите опцию Color Theme. Чтобы настроить иконки, можете выбрать опцию File Icon Theme.
Расширения для тех, кто интересуется FrontEnd-фреймворками для веб-разработки, такими как Angular и React:
- (Необязательно) Angular Language Service от Angular.
- (Необязательно) Angular Snippets от John Papa.
- (Необязательно) ES7 React / Redux / GraphQL / React-Native snippets от dsznajder.
- (Необязательно) React Native Tools от Microsoft.
- (Необязательно) Live Server от Ritwick Dey.
Итак, мы уже установили VS Code и несколько расширений. Теперь мы готовы настраивать среду разработки. Я создал шаблон для спортивного программирования в VS Code и загрузил его в свой профиль на Github.
Перейдите по этой ссылке и загрузите шаблон себе на компьютер. Распакуйте его в любое место по вашему выбору. После этого откройте получившуюся папку в VS Code. Вы должны увидеть что-то вроде этого:
Пройдитесь по файлам main.cpp, Main.java и main.py и посмотрите на записанный в них образец кода. По сути, шаблонный код, предоставленный в образцах для каждого из этих трех языков, принимает входящие данные из файла input.txt и обеспечивает вывод в файл output.txt. Для каждой программистской задачи, которую вы хотите решить, просто создайте копию этого шаблона и напишите свой код в функции solve().
Теперь создадим ту разбивку экрана, которую вы могли видеть на самом первом изображении в этой статье. Эта разбивка позволяет сразу видеть как ввод, так и вывод вашего кода, что делает ее очень удобной в использовании.
- Откройте файлы в следующем порядке: main.cpp, input.txt, output.txt. Порядок, в каком были открыты файлы, можно видеть сверху на панели инструментов. Убедитесь, что порядок именно такой, как указано выше.
- Откройте input.txt. Выберите в меню View -> Editor Layout -> Split Right. Вы должны увидеть что-то подобное:
- У вас получится две группы. Перетащите output.txt из левой группы в правую. Закройте тот input.txt, что остался слева. Должно выйти примерно так:
- Далее откройте output.txt в правой группе. Выберите View -> Editor Layout -> Split Down. Уберите output.txt из верхней группы. После этого вы увидите:
Готово! Мы настроили внешний вид редактора. А теперь давайте запускать код.
Для запуска нашего кода мы будем использовать расширение Code Runner, потому что ручная настройка VS Code для каждого языка — весьма сложная задача и потребует много затрат времени и сил.
Прежде чем использовать это расширение, нам нужно настроить его так, чтобы оно работало через терминал, иначе мы не сможем обеспечить консольный ввод нашего кода. Эти шаги очень важно проделать в точности:
- Выберите File -> Preferences -> Settings.
- Введите “code runner run in terminal” в поле поиска и установите галку в чекбоксе:
По умолчанию Code Runner не добавляет флаг -std=c++14 при компиляции кода. Это ограничивает ваши возможности как программиста. Например, если вы попытаетесь сделать так:
То это вызовет предупреждение: “Расширенные списки инициализаторов доступны только с -std=c++11 или -std=gnu++11”.
Выполните следующие действия, чтобы добавить флаг:
- Выберите File -> Preferences -> Settings.
- Введите в поиске “Run Code Configuration”.
- Определите местонахождение “Code-runner: Executor Map” и выберите “Edit in settings.json”. Это откроет файл settings.json. Добавьте туда следующий код:
Наконец-то всё настроено для запуска ваших программ на C++, Java и Python.
Откройте файл main.cpp. Нажмите правую кнопку мыши и выберите опцию Run Code. Попробуйте напечатать что-нибудь в функции solve(), чтобы проверить, происходит ли у вас вывод в файл output.txt или нет.
Следуйте той же процедуре с файлами Main.java и main.py. Расширение Code Runner возьмет на себя выполнение каждого из них.
Я надеюсь, что эта статья помогла вам настроить Visual Studio Code. Счастливого программирования!
Читайте также: