在Maven项目中,我想将一些测试结果写入项目目标目录中的文件中。每当我得到项目目录时,它实际上是在获取IntelliJ项目目录,而不是实际的Maven目录。
我得到了这个问题的解决方案。这是我的实施方式。我有自己的 CSVReader 类,它使用 CSVReader 库。我正在将结果写入目标目录下的 results.csv 文件中。
URL location = CSVReader.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().replace("classes/","") + "results.csv";
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我获取目标目录路径并通过字符串替换方法删除classes/并附加我想要的文件名。希望这可以帮助某人。
您还可以使用java.nio.file.Paths:
URL url = Paths.get("target", "results.csv").toUri().toURL();
Run Code Online (Sandbox Code Playgroud)
小智 5
我稍微修改了上面的答案(我无法添加评论)。由于测试放置在“test”文件夹中,它们的类将驻留在“target/test-classes”中(因此替换“classes”可能不会给您预期的结果)。相反,我使用了以下内容:
File targetClassesDir = new File(ExportDataTest.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8493 次 |
| 最近记录: |