Returns the working directory of the given class (its usually the target dir). - Java java.nio.file

Java examples for java.nio.file:Path

Description

Returns the working directory of the given class (its usually the target dir).

Demo Code


//package com.java2s;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.security.CodeSource;
import java.security.ProtectionDomain;

public class Main {
    /**//from w  w w.j  a  v  a2  s.co m
     * Returns the working directory of the given class (its usually the target
     * dir). Works also in jar files.
     */
    public static String getWorkingDirectory(Class<?> clazz) {
        ProtectionDomain domain = clazz.getProtectionDomain();
        CodeSource codeSource = domain.getCodeSource();
        Path file = Paths.get(codeSource.getLocation().getPath())
                .toAbsolutePath();

        if (Files.exists(file)) {
            Path parent = file.getParent();

            return parent.toString();
        }

        return null;
    }
}

Related Tutorials