Java获取当前项目文件路径、项目编译路径、获取项目根路径
方式如下:
内容打印代码如下:
package com.mysqld;
import java.io.File;
import java.net.URL;
public class FilePath {
public static void main(String[] args) {
// TODO Auto-generated method stub
new FilePath().getpath();
}
public void getpath() {
File f = new File(this.getClass().getResource("/").getPath());
//结果 D:\java\javaproject\swing-easy-code-1.0\bin
System.out.println(f);
File f1 = new File(this.getClass().getResource("").getPath());
//结果:D:\java\javaproject\swing-easy-code-1.0\bin\com\mysqld
System.out.println(f1);
//项目工程的src下面的文件,存在则有,不存在则没有
URL xmlpath = this.getClass().getClassLoader().getResource("test.txt");
//结果:file:/D:/java/javaproject/swing-easy-code-1.0/bin/test.txt
//获取工程路径src下面文件的项目位置
//如果文件不存在则返回null
System.out.println(xmlpath);
//结果:D:\java\javaproject\swing-easy-code-1.0
System.out.println(System.getProperty("user.dir"));
}
}
第一种:获取当前类的所在工程(编译)路径
public class ProjectPath {
public void getPath() {
File f = new File(this.getClass().getResource("/").getPath());
//是编译项目都是java路径所在位置
System.out.println(f);
}
}
结果:
D:\java\javaproject\swing-easy-code-1.0\bin
第二种:获取项目的相对路径(是当前文件所在位置)
package com.mysqld;
import java.io.File;
public class Myc {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Myc().getpath();
}
public void getpath() {
//当前获取的项目是当前的java文件所在编译后的位置
File f = new File(this.getClass().getResource("").getPath());
System.out.println(f);
}
}
结果:com.mysqld是包,com.mysql
D:\java\javaproject\swing-easy-code-1.0\bin\com\mysqld
第三种:获取当前工程src目录下selected.txt文件的路径
public void getpath() {
URL xmlpath = this.getClass().getClassLoader().getResource("test.txt");
//获取工程路径src下面文件的项目位置
//如果文件不存在则返回null
System.out.println(xmlpath);
}
结果:
file:/D:/java/javaproject/swing-easy-code-1.0/bin/test.txt
第四种:获取当前工程路径
//获取当前项目所在工程的,位置,也是项目的根路径
System.out.println(System.getProperty("user.dir"));
结果:swing-easy-code-1.0是java项目的名字
D:\java\javaproject\swing-easy-code-1.0