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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38558720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:31:57  来源:igfitidea点击:

Get the target directory path in Maven (Java)

javamaven

提问by vkrams

In a Maven project I want write some test results into a file in target directory of the project. Whenever, I get the project directory, it is actually getting the IntelliJ project directory instead of actual Maven directory.

在 Maven 项目中,我想将一些测试结果写入项目目标目录中的文件中。每当我获取项目目录时,它实际上是获取 IntelliJ 项目目录而不是实际的 Maven 目录。

采纳答案by vkrams

I got the solution for this. Here is how I am implementing. I have my own class CSVReader which uses CSVReader library. I am writing my results in results.csv file under target directory.

我得到了解决方案。这是我的实施方式。我有自己的类 CSVReader,它使用 CSVReader 库。我正在将结果写入目标目录下的 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. Hope this might help someone.

在上面的代码中,我正在获取目标目录路径并通过字符串替换方法删除 classes/ 并附加我想要的文件名。希望这可以帮助某人。

回答by twalthr

You could also use java.nio.file.Paths:

您还可以使用java.nio.file.Paths

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

回答by Mia Mano

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). Instead, I used the following:

我稍微修改了上面的答案(我无法添加评论)。由于测试放置在“test”文件夹中,它们的类将驻留在“target/test-classes”中(因此替换“classes”可能不会给您预期的结果)。相反,我使用了以下内容:

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