简体   繁体   中英

Debugging Java programs with command line arguments from Visual Studio Code

I'm using the "Extension Pack for Java" by Microsoft. It works fine, I can add new class files, compile, run and debug them. If I run extension command "Java: Create Java Project" I get a nice setup with subfolders for libraries, "binaries" and source, ie ./lib, ./bin, ./src.

However, now I need to call a program with command line arguments.

I can go to the terminal and run the program with command line arguments:

java.\src\HelloWorld.java Argument1 Argument2

or compile it in VSC and run it from terminal using:

java.\bin\ HelloWorld Argument1 Argument2

However, how can I add the arguments when starting the application from VSC? (running and/or debugging).

I've seen and tried quite a few guides on setting up various.json "settings" files for VSC but none of them seem to match the Java Extension pack setup.

What is the simplest possible solution? (simple as in fewest possible text lines in.json file).

To run a Java program with command line arguments from Visual Studio Code, you can use the "Launch" configuration in the Debug panel. This allows you to specify the arguments that you want to pass to the program when it is launched.

Here's an example of how you can set this up:

  1. Open the Debug panel in Visual Studio Code by clicking on the Debugging icon in the left sidebar, or by using the CTRL+SHIFT+D keyboard shortcut.

  2. Click on the dropdown menu next to the "Start Debugging" button, and select "Add Configuration..."

  3. In the launch.json file that opens, add a new configuration for your Java program. For example:

{
    "name": "Hello World",
    "type": "java",
    "request": "launch",
    "mainClass": "src/HelloWorld",
    "args": "Argument1 Argument2"
}
  1. Save the file, and start debugging your program by clicking on the "Start Debugging" button. The program will be launched with the specified command line arguments.

Note that in the above example, the mainClass property specifies the path to the main class of your program, relative to the project root. This should be the same path that you use when running the program from the terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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