Tuesday 14 December 2021

How to specify jar files in command line?

Java takes the current directory as default classpath, you can customize this using -cp option.

 

Syntax

In Linux and MAC systems

javac -cp jar1:jar2:jar3:dir1:dir2:. HelloWorld.java
java -cp jar1:jar2:jar3:dir1:dir2:. HelloWorld

 

In Windows systems

javac -cp jar1;jar2;jar3;dir1;dir2;. HelloWorld.java
java -cp jar1;jar2;jar3;dir1;dir2;. HelloWorld

 

Let’s see it with an example.

 

PrettyJson.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class PrettyJson {

	public static void main(String args[]) {
		String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		JsonElement jsonElement = JsonParser.parseString(uglyJson);
		String prettyJsonString = gson.toJson(jsonElement);

		System.out.println(prettyJsonString);
	}

}

 

In my case gson-2.8.9.jar library is located at '/Users/Shared/jars/' folder.

$javac -cp /Users/Shared/jars/gson-2.8.9.jar:. PrettyJson.java 
$
$java -cp /Users/Shared/jars/gson-2.8.9.jar:. PrettyJson
{
  "name": "Krishna",
  "age": 31
}

 


 

   

You may like

Interview Questions

volatile reference vs Atomic references defined in java.util.concurrent.atomic package

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

No comments:

Post a Comment