一般我们会使用.class方法用来获取文件的相对路径。如下:
String fileName = this.getClass().getClassLoader().getResource("文件名").getPath();//获取文件路径
String fileUtl = this.getClass().getResource("文件名").getFile();
但是,这样的方式来获取文件的路径,都是获取target文件夹下的路径,因为.class的加载机制问题,我们使用这种方法会得到被编译后的文件路径。会出现如下:
出现的都是target下的classes这样的目录。创建成功后的文件会出现在.class文件夹下
因此,我们需要使用拼接的方法。
使用这个方法会得到文件的路径。
//获得文件的路径
System.getProperty("user.dir")
拼接我们想要放到文件的路径
public static void main(String[] args) throws IOException {
// E:\Login\iostream\src\main\resources
String fileADD = System.getProperty("user.dir") + "/src/main/resources/aa.txt";
File file1=new File(fileADD);
System.out.println(file1.createNewFile());
}
文件成功创建。