java 获取项目根路径的3种实现方式

1.情景展示

在java开发过程中,如何获取当前项目所在的磁盘路径(绝对路径)和桌面路径?

2.获取项目根路径

第一种方式:纯java项目

如果是main方法运行,可以使用这种方式。

System.getProperty("user.dir")

如果是web项目,就不能使用这种方式了。

它获取的是eclipse所在目录,而不是项目路径。

项目的实际路径为:

/**
 * 得到当前文件所在硬盘根目录
 * WINDOWS:C:/  OR  D:/  OR  E:/ + twrs_logs/
 * LINUX  :/ + twrs_logs/
 * @return
 */
public static String getRootPath(){
	
	// Windows:取当前程序部署硬盘的根目录 + twrs/twrs_logs/
	// Linux  :由于权限问题,不能直接取根目录,要取当前用户主目录 + twrs/twrs_logs/
	String os_name = System.getProperties().getProperty("os.name");
    if (os_name.indexOf("Windows") >= 0) {
    	URL path = FileUtils.class.getClassLoader().getResource("");
    	String relPath  = path.getPath();
    	return relPath.substring(0, relPath.indexOf(":/") + 2).concat("twrs/twrs_logs/");
    } else {
    	return System.getProperty("user.home").concat("/twrs/twrs_logs/");
    }
}

第二种方式:Class.getResource("/").getPath()

在非静态方法中调用:

this.getClass().getResource("/").getPath()

在静态方法中调用:

类名.class.getResource("/").getPath();

具体实现:

// 获取项目所在磁盘路径(绝对路径)
String classPath = this.getClass().getResource("/").getPath();
String projectPath = classPath.substring(1);
// 判断,项目路径当中是否包含:/web/
int webIndex = projectPath.indexOf("/web/");
// 项目路径包含:/web/
if (projectPath.indexOf("/web/") > 0 || projectPath.indexOf("/WebContent/") > 0 || projectPath.indexOf("/WebRoot/") > 0) {
    projectPath = projectPath.substring(0, webIndex);
} else {
// TODO
}
// wj_task_error.log所在路径
String taskLogPath = projectPath + File.separator + "logs" + File.separator + "wj_task_error.log";

说明:

projectPath的最终值,就是项目的路径。

web目录是javaWeb项目的存储项目文件的根目录(MyEclipse创建的web项目,默认是:WebRoot;Eclipse是WebContent) 。

这里改成你实际使用的目录名称即可(/web/)。 

我们可以看到:

此时,该日志文件的所在路径是对的。

第三种方式:Class.getClassLoader.getResource("").getPath()

在非静态方法中调用

this.getClass().getClassLoader().getResource("").getPath();

在静态方法中使用

类名.class.getClassLoader().getResource("").getPath();

具体实现:

// 获取项目所在磁盘路径(绝对路径)
String classPath = this.getClass().getClassLoader().getResource("/").getPath();
String projectPath = classPath.substring(1);
// 判断,项目路径当中是否包含:/web/
int webIndex = projectPath.indexOf("/web/");
// 项目路径包含:/web/
if (webIndex > 0) {
    projectPath = projectPath.substring(0, webIndex);
}

// wj_task_error.log所在路径
String taskLogPath = projectPath + File.separator + "logs" + File.separator + "wj_task_error.log";

小结:

方式二和方式三都是通过当前运行的class类,找到了对应的classes目录。 

3.获取桌面路径

FileSystemView.getFileSystemView().getHomeDirectory().getPath();

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐:

posted @ 2021-12-15 10:35  Marydon  阅读(1558)  评论(0编辑  收藏  举报