Search code examples
javajsonvisual-studio-codecmdorg.json

Compiling java program with external libraries from command line


I am having difficulty compiling my java program from the command line. The program uses external libraries and I have had no issues compiling the program. However, upon running the program, the following error is generated:

C:\Users\...\App> javac -d bin -cp lib/json.jar src/*.java

C:\Users\...\App> java src/App.java
src\App.java:3: error: package org.json does not exist
import org.json.*;
^
src\App.java:35: error: cannot find symbol
            JSONObject obj = new JSONObject(jsonString);
            ^
  symbol:   class JSONObject
  location: class App
src\App.java:35: error: cannot find symbol
            JSONObject obj = new JSONObject(jsonString);
                                 ^
  symbol:   class JSONObject
  location: class App
3 errors
error: compilation failed

C:\Users\...\App> 

The file structure looks like this:

enter image description here

How can I compile my program with its external libraries from the command line?

UPDATE

I've rearranged the file structure as advised and is now

enter image description here

However, I am still getting errors when compiling the program

C:\Users\...\App\src>javac -d ..\bin -cp lib\json.jar App.java

C:\Users\...\App\src>java -cp ..\bin:.\lib\json.jar App.java
App.java:3: error: package org.json does not exist
import org.json.*;
^
App.java:35: error: cannot find symbol
            JSONObject obj = new JSONObject(jsonString);
            ^
  symbol:   class JSONObject
  location: class App
App.java:35: error: cannot find symbol
            JSONObject obj = new JSONObject(jsonString);
                                 ^
  symbol:   class JSONObject
  location: class App
3 errors
error: compilation failed

Solution

  • It's not java xxx.java, it's java SomeNameoOfTheClassFileName.

    You can just click the add button on the right of Referenced Libraries under the Java Projects panel:

    enter image description here

    Then you can import the org.json.* successfully. Then you can click the Run Java button on the top-right of the VSCode, the Java extension will help you compile the java code automatically.

    Or you just want to compile the java file manually, you can read this article.

    Depending on the first picture's structure it will be like this:

    First

    javac -cp lib\json.jar -d classes src\App.java
    

    After that, create a manifest.txt next to README.md and contains:

    Main-Class: App  //if your App.java has package src, it will be src.App
    Class-Path: lib\json.jar
    //need keep a blank line here
    

    Then

    jar cfm App.jar manifest.txt -C classes .
    

    Last

    java -jar App.jar