Include gson in my java program

So far, I have used only standard libraries in my programs. I just create a simple console application, and I do not use the IDE, just a simple text editor (because at the moment I do not need something more complicated).

I don’t know where to put the jar file that I downloaded, and I also don’t know how to name it correctly. Did I read something about turning on the path? But I'm not sure if I understand.

I just have a simple folder structure:

  • Project
    • Class.java
    • Class.class
    • gson-2.2.1.jar

I tried with this:

import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonParser; 

But I understand that it does not exist.

+4
source share
2 answers

This answer assumes that you are using javac and java commands in a * nix environment.

To compile your code, you must put the jar and your Java files in the classpath with the -cp flag. For this small example, you really need to provide a Java file that has your main method. This is because the compiler will look for any Java files that it should compile with YourClass.java by looking for them in the class path.

 javac -cp /path/to/java/files:/path/to/gson-2.2.1.jar YourClass.java 

To run the code, you need to do the same, but access the class only using the main method.

 java -cp /path/to/class/files:/path/to/gson-2.2.1.jar YourClass 

Keep in mind that the directories /path/to/java/files and /path/to/class/files should point to the root directory of your packages (if you use the packages you need).

+6
source

set the class path to both the current directory ( . ) (therefore, the compiler will find your class) and gson-2.2.1.jar (therefore, the compiler will find classes inside this jar)

The class path is similar to the PATH evnrionmental variable, and you will need different delimiters for different operating systems ( : for * nix and ; for Windows) - at least for javac

For javac, you can set the classpath directly by specifying the -cp option. Alternatively, set the environment variable CLASSPATH (as with PATH env. Var.)

0
source

Source: https://habr.com/ru/post/1413213/


All Articles