简体   繁体   English

在 Maven (Java) 中获取目标目录路径

[英]Get the target directory path in Maven (Java)

In a Maven project I want write some test results into a file in target directory of the project.在 Maven 项目中,我想将一些测试结果写入项目目标目录中的文件中。 Whenever, I get the project directory, it is actually getting the IntelliJ project directory instead of actual Maven directory.每当我获取项目目录时,它实际上是获取 IntelliJ 项目目录而不是实际的 Maven 目录。

你也可以使用java.nio.file.Paths

URL url = Paths.get("target", "results.csv").toUri().toURL();

I used the answer above with a slight modification (I can't add comments).我稍微修改了上面的答案(我无法添加评论)。 Since tests are placed into the 'test' folder, their classes will reside in 'target/test-classes' (so replacing 'classes' might not give you the expected result).由于测试放置在“test”文件夹中,它们的类将驻留在“target/test-classes”中(因此替换“classes”可能不会给您预期的结果)。 Instead, I used the following:相反,我使用了以下内容:

File targetClassesDir = new File(ExportDataTest.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();

I got the solution for this.我得到了解决方案。 Here is how I am implementing.这是我的实施方式。 I have my own class CSVReader which uses CSVReader library.我有自己的类 CSVReader,它使用 CSVReader 库。 I am writing my results in results.csv file under target directory.我正在将结果写入目标目录下的 results.csv 文件。

URL location = CSVReader.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().replace("classes/","") + "results.csv";

In the above code I am getting the target directory path and removing the classes/ by string replace method and appending my desired file name.在上面的代码中,我正在获取目标目录路径并通过字符串替换方法删除 classes/ 并附加我想要的文件名。 Hope this might help someone.希望这可以帮助某人。

I'm using the classloaders root resource path for retrieving projects build directory with following single line:我正在使用类加载器根资源路径来检索项目构建目录,其中包含以下单行:

Path targetPath = Paths.get(getClass().getResource("/").toURI()).getParent();

The root resource path points to test-classes and it's parent is the desired path regardless of running the test via maven surefire or a JUnit runner of the IDE like Eclipse.根资源路径指向test-classes ,无论是通过 maven surefire 还是 IDE 的 JUnit 运行程序(如 Eclipse)运行测试,它的父资源都是所需的路径。

The following solutions work for me:以下解决方案对我有用:

URL location = YourClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().replace("/test-classes/","").replace("/classes/","");

or

Path targetPath = Paths.get(getClass().getResource("/").toURI()).getParent();
String path = targetPath.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM