Tuesday, April 21, 2015

Java Working Directory - Wrong GDD

Lately I spend almost a day, actually a whole day to figure out jar file running directory. Actually what I needed was 'System.getProperty("user.dir")'



Here is the function first I wrote which worked across Mac, Linux and Windows 8

private static String workingDirectory() {
  File currentJavaJarFile = new File(<any>Util.class
                            .getProtectionDomain()
                            .getCodeSource()
                            .getLocation()
                            .getPath());
  String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();
  String parentDir = currentJavaJarFile.getParent();
  String jarFilename = currentJavaJarFile.getName();
  parentDir = parentDir.toString().replace("\\", "\\\\"); //backslash directory separator error in windows
  String directory = currentJavaJarFilePath.replaceAll(parentDir.toString(), "").replace((File.separator + jarFilename), "");
  return directory;

No comments:

Post a Comment