Sunday, 26 May 2019

Java: Get the path of running Java class


Below snippet returns the absolute path of running java class.
URI uri = App.class.getProtectionDomain().getCodeSource().getLocation().toURI();

App.java
package com.sample.app;

import java.net.URI;
import java.net.URISyntaxException;

public class App {

 public static void main(String args[]) throws URISyntaxException {

  URI uri = App.class.getProtectionDomain().getCodeSource().getLocation().toURI();

  System.out.println("uri : " + uri );
 }

}

If the path has any spaces, special characters use URLDecoder.decode method.
String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "utf-8");


App.java
package com.sample.app;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class App {

 public static void main(String args[]) throws UnsupportedEncodingException {

  String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath();
  String decodedPath = URLDecoder.decode(path, "utf-8");
  
  System.out.println("path : " + path );
  System.out.println("decodedPath : " + decodedPath );
 }

}


You may like

No comments:

Post a Comment