public class Test {
public static void main(String... args) throws Exception {
URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());
}
}
One way would be to use the 系统属性系统属性System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.
下面的代码将打印调用该命令的工作目录,而不管。班级或。Jar 文件。类文件在。
public class Test
{
public static void main(final String[] args)
{
final String dir = System.getProperty("user.dir");
System.out.println("current dir = " + dir);
}
}
如果您在 /User/me/中,并且包含以上代码的.jar 文件在 /opt/some/nested/dir/中
命令 java -jar /opt/some/nested/dir/test.jar Test将输出 current dir = /User/me。