java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java获取当前项目文件路径、项目编译路径

Java获取当前项目文件路径、项目编译路径的几种方法

作者:詠聖wK

文章浏览阅读2w次,点赞14次,收藏41次。本文详细介绍了五种在Java中获取项目路径的方法,包括获取当前类所在工程编译路径、工程路径、src目录下特定文件路径等,适用于不同场景的需求。

第一种:获取当前类的所在工程(编译)路径

File f = new File(this.getClass().getResource("/").getPath());
System.out.println(f);

结果:

C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin

在IDEA下测试可以得到工程编译的路径:

/Users/yswKnight/Documents/SourceTree/projectName/webapp/WEB-INF/classes

如果不加“/”,获取当前类的绝对路径

File f = new File(this.getClass().getResource("").getPath());
System.out.println(f);

结果:

C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin\com\test

第二种:获取当前类的所在工程路径

File directory = new File("");//参数为空
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);

结果:

C:\Documents and Settings\Administrator\workspace\projectName

第三种:获取当前工程src目录下selected.txt文件的路径

URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt");
System.out.println(xmlpath);

结果:

file:/C:/Documents%20and%20Settings/Administrator/workspace/projectName/bin/selected.txt

第四种:获取当前工程路径

System.out.println(System.getProperty("user.dir"));

结果:

C:\Documents and Settings\Administrator\workspace\projectName

第五种:获取当前工程路径

System.out.println( System.getProperty("java.class.path"));

结果:

C:\Documents and Settings\Administrator\workspace\projectName\bin

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文