我有一个具有这种结构的项目
data_folder/
myProject
module1
main/java
test/java
pom.xml
module2
...
pom.xml
我想使用测试类和主类访问data_folder
。
在测试类中,可以使用
new File("data_folder/myfile.txt")
但是在主类中,只能使用
new File("../data_folder/myfile.txt")
这些文件必须位于类路径之外,因为它们是可编辑的。有没有更好的方法来做到这一点?
最佳答案
执行此操作的常见方法是在启动程序/测试时将 data_folder 的完整位置作为参数传递:
-DFILES_LOCATION=/somelocation/data_folder
然后访问并创建如下文件:
String root_dir = System.getProperty("FILES_LOCATION");
File myFile = new File(rootDir+File.separator+"myfile.txt")
那么它是否是相对路径并不重要 - 您只需指向输入/数据文件所在的位置即可。
关于java - 使用主类和测试类读取相对路径(类外部路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34659017/