在Maven项目中,我想将一些测试结果写入到项目目标目录中的某个文件中。每当我获取项目目录时,实际上会获取IntelliJ项目目录而不是真正的Maven目录。
你也可以使用java.nio.file.Paths
:
URL url = Paths.get("target", "results.csv").toUri().toURL();
URL location = CSVReader.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().replace("classes/","") + "results.csv";
我使用了上面的答案,并做了一点修改(我无法添加评论)。 由于测试被放置在“test”文件夹中,它们的类将驻留在“target/test-classes”中(因此替换“classes”可能不会给您预期的结果)。相反,我使用了以下内容:
File targetClassesDir = new File(ExportDataTest.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();
我正在使用类加载器的根资源路径来检索项目构建目录,以下是使用单行代码实现的:
Path targetPath = Paths.get(getClass().getResource("/").toURI()).getParent();
test-classes
,其父路径是所需路径,无论是通过Maven Surefire还是诸如Eclipse之类的IDE的JUnit运行器运行测试。URL location = YourClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().replace("/test-classes/","").replace("/classes/","");
或者
Path targetPath = Paths.get(getClass().getResource("/").toURI()).getParent();
String path = targetPath.toString();
你需要获取类的位置,以便在运行逻辑时获得目标路径的位置。我使用以下代码来实现这一目标:
URL target = this.getClass().getClassLoader().getResource("org/mycomp/home/model").toURI().toURL();