【发布时间】:2018-06-19 12:50:30
【问题描述】:
我需要在应用程序中捕获一些目录。为此,我做了一个小演示:
String pkgName = TestClass.class.getPackage().getName();
String relPath = pkgName.replace(".", "/");
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
File file = new File(resource.getPath());
System.out.println("Dir exists:" + file.exists());
从 IDE 运行应用程序时,我收到了我的目标,我可以找到我的目录。但是将应用程序作为 JAR 文件运行,不会返回有效的“文件”(从 Java 的角度来看),我的 sout 还给了我File exists:false。有没有办法得到这个文件?在这种情况下,文件是一个目录。
【问题讨论】:
-
你能检查一下 System.out.println(new File(".").getAbsolutePath()); 的输出吗?在这两种情况下。并将其添加到评论中。
-
System.out.println(new File(".").getAbsolutePath());总是返回项目文件夹的绝对路径,例如在 Windows 'C:\Users\name\path\to\project\folder\.'