[Java SE] Java-文件系统-常用文件路径的获取方法

目录

1 获取相对路径

/**
 * 获取相对路径 【推荐】
 * 使用Java提供的Path类和Paths类来获取相对路径。
 * 例如,假设有两个路径a和b,我们可以使用Path类的relativize()方法来获取相对路径,该方法返回一个相对路径的Path对象。
 */
@Test
public void getRelativePathTest1(){
	Path pathA = Paths.get("/user/myproject/dir1");//不需要保证文件实际存在
	Path pathB = Paths.get("/user/myproject/dir2/subdir/file.txt");//不需要保证文件实际存在

	Path relativePathB = pathA.relativize(pathB);//[√]
	log.info("relativePathB : {}", relativePathB);// "relativePathB : ..\dir2\subdir\file.txt"

	Path relativePathA = pathB.relativize(pathA);
	log.info("relativePathA : {}", relativePathA);// "relativePathA : ..\..\..\dir1"
}

/**
 * 获取相对路径 【推荐】
 */
@Test
public void getRelativePathTest2() throws IOException {
	File fileA = new File("/user/myproject/dir1");//不需要保证文件实际存在
	File fileB = new File("/user/myproject/dir2/subdir/file.txt");//不需要保证文件实际存在

	String absolutePathA = fileA.getCanonicalPath();//E:\\user\\myproject\\dir1
	String absolutePathB = fileB.getCanonicalPath();//E:\\user\\myproject\\dir2\\subdir\\file.txt
	String relativePath = absolutePathB.substring(absolutePathA.length()); // 输出:/dir2/subdir/file.txt

	log.info("absolutePathA : {}, absolutePathB : {}", absolutePathA, absolutePathB);//absolutePathA : E:\\user\\myproject\\dir1, absolutePathB : E:\\user\\myproject\\dir2\\subdir\\file.txt
	log.info("relativePath : {}", relativePath);//relativePath : \\subdir\\file.txt
}

/**
 * 获取相对路径
 * 如果是在Web应用中获取相对路径,可以使用ServletContext的getRealPath()方法来获取文件的绝对路径,然后使用字符串的截取来获取相对路径。
 */
//    @Test
//    public void getRelativePathTest3(){
//        ServletContext servletContext = null;
//        String absolutePathA = servletContext.getRealPath("/dir1");
//        String absolutePathB = servletContext.getRealPath("/dir2/subdir/file.txt");
//        String relativePath = absolutePathB.substring(absolutePathA.length()); // 输出:/dir2/subdir/file.txt
//    }

2 获得绝对路径

基于相对路径获得绝对路径

@Test
public void getAbsolutePathByRelativePathTest(){
	// 相对路径
	String relativePath = "example.txt";

	// 获取绝对路径
	String absolutePath = null;
	//方式1
	//absolutePath = ( new File(relativePath) ).getAbsolutePath( );//E:\source_code\ADP\poc-bigdata\poc-common-demo\example.txt

	//方式2
	//absolutePath = ( (Path) Paths.get(relativePath)).toAbsolutePath().toString();//E:\source_code\ADP\poc-bigdata\poc-common-demo\example.txt

	/**
	 * 方式3 【推荐】
	 * ClassLoader 提供的 getResource()方法可以获取资源文件的URL。通过 URL 对象的 getPath 方法可以获取文件的绝对路径
	 */
	//absolutePath = getAbsolutePath(ClassLoader.getSystemClassLoader(), relativePath);

	//方式4 【推荐】 基于基础参考路径、相对路径,拼接出文件的绝对路径
	String classpath = ClassLoader.getSystemResource("").getPath();//如: /E:/source_code/xxx/xxx-bigdata/xxx-common-demo/target/classes/
	absolutePath = getAbsolutePath( classpath, relativePath );

	//方式5 通过 javax.servlet.ServletContext#getRealPath(relativePath) 方法
	//ServletContext servletContext = null;//获取 servletContext 对象,此处省略获取过程
	//absolutePath = servletContext.getRealPath(relativePath);

	// 输出绝对路径
	System.out.println("absolutePath: " + absolutePath);
}

/**  
 * 通过 classloader 、相对路径,获得绝对路径  
 * @param relativePath  
 * @param classLoader  
 *   [1] 获取ClassLoader的方式  
 *   ClassLoader classLoader = ClassLoader.getSystemClassLoader();  
 *   ClassLoader classLoader = Thread.currentThread().getContextClassLoader() *   ClassLoader classLoader = XXClass.class.getClassLoader(); 
 * @return
 */
  public String getAbsolutePath(ClassLoader classLoader, String relativePath){  
    String absolutePath = null;  
  
    URL resource = classLoader.getResource(relativePath);// ClassLoader.getSystemResource(relativePath);  
  
    if(resource != null){  
        absolutePath = resource.getPath();  
    } else{  
        log.warn("the relative path's resource not for classpath!relativePath:{}", relativePath);  
    }  
    return absolutePath;  
}  
  
/**  
 * 通过 基础参考路径 、相对路径,获得绝对路径  
 * @param relativePath 注:路径的首个字符不得含有文件夹符号  
 * @param basePath 注: 路径的最后必须含文件夹符号 [ "/"(Linux) , "\"(Windows) ]  
 * @return
 */
public String getAbsolutePath(String basePath, String relativePath) {  
    //File.separator  
    return basePath + relativePath;  
}

3 获取 classpath 路径

public class ClassPathDemo {  
    public static void main(String[] args) {  
        String classpath = null;  
  
        //方式1  
        classpath = System.getProperty("java.class.path");//classpath:D:\Program\Java\jdk1.8.0_261\jre\lib\charsets.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\deploy.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\access-bridge-64.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\cldrdata.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\dnsns.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\jaccess.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\jfxrt.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\localedata.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\nashorn.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\sunec.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\sunjce_provider.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\sunmscapi.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\sunpkcs11.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\ext\zipfs.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\javaws.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\jce.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\jfr.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\jfxswt.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\jsse.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\management-agent.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\plugin.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\resources.jar;D:\Program\Java\jdk1.8.0_261\jre\lib\rt.jar;E:\source_code\xxx\xxx-bigdata\xxx-common-demo\target\classes;D:\Program\IDEA\IDEA_COMMUNITY_2023.2\lib\idea_rt.jar  
  
        //方式2  
        //String classpath = ClassPathDemo.class.getResource("/").getPath();//out : 同方式1  
  
        //方式3 【推荐】  
        //classpath = ClassLoader.getSystemResource("").getPath();//classpath:/E:/source_code/xxx/xxx-bigdata/xxx-common-demo/target/classes/  
  
        //方式4 | 仅适用于 servlet web 项目  
        //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();  
        //classpath = context.getResource("").getFile().getAbsolutePath();  
        System.out.println("classpath:" + classpath);  
    }  
}

4 获取当前工程根路径

  • 在Java程序中,可以通过System.getProperty("user.dir")来获取当前工作目录的路径,即程序运行时所在的目录。这个属性通常用于读取或写入文件时指定文件相对路径,以便程序能够正确找到文件。
  • 举例说明,如果当前工作目录是/Users/username/Documents,那么System.getProperty("user.dir")将返回/Users/username/Documents。
//获取当前工作目录的路径  
//String projectRootPath = ( new File("") ).getCanonicalPath();//方式1  
String projectRootPath = System.getProperty("user.dir");//方式2  
System.out.println("projectRootPath :" + projectRootPath);//E:\source_code\xxx\xxx-yy

5 获取用户主目录

String userHomePath = null;  
userHomePath = org.apache.commons.io.FileUtils.getUserDirectoryPath();
// 等效于 : System.getProperty("user.home");System.out.println("userHomePath :" + userHomePath);
//C:\Users\xxxx

6 获取OS临时目录

String tempDirectoryPath = FileUtils.getTempDirectoryPath();
//等效于 : System.getProperty("java.io.tmpdir")System.out.println("tempDirectoryPath :" + tempDirectoryPath);
// C:\\Users\\xxxx\\AppData\\Local\\Temp\\

Y 获取指定路径文件的 URL/InputStream 对象

  • 前提说明
XXServiceBizApplication 的路径 : src/main/java/com.xx.yy.zz.biz.XXServiceBizApplication
FileTest 的路径 : src/test/java/com.test.FileTest

Object 的路径 : java.lang.Object
Thread 的路径 : java.lang.Thread

messages_en_US.propertie 的路径 : src/main/resources/i18n/messages_en_US.properties


URL|InputStream : java.lang.Class#getResource(path)|getResourceAsStream(String path)

  • (1)不以 / 开头时,默认:以当前class类文件所在路径为基准,目标文件相对于该类文件的路径
URL url = XXServiceBizApplication.class.getResource("");//获得当前class类文件的URI目录,不包括类文件自己!
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/com/xx/yy/zz/biz

Thread.currentThread().getContextClassLoader().getResource("")
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/

URL url = XXServiceBizApplication.class.getResource("./../../../../../i18n/messages_en_US.properties");
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/i18n/messages_en_US.properties

URL url = Object.class.getResource("./../../i18n/messages_en_US.properties");//Object 的路径 : java.lang.Object
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/i18n/messages_en_US.properties

InputStream inputStream = XXServiceBizApplication.class.getResourceAsStream("./../../../../../i18n/messages_en_US.properties");
  • (2)以 / 开头,则:从 ClassPath 根下获取。
URL url = XXServiceBizApplication.class.getResource("/");//当前的classpath的绝对URI路径
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/

URL url = XXServiceBizApplication.class.getResource("/i18n/messages_en_US.properties");
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/i18n/messages_en_US.properties

InputStream inputStream = XXServiceBizApplication.class.getResourceAsStream("/i18n/messages_en_US.properties");

URL|InputStream : java.lang.ClassLoader#getResource(path)|getResourceAsStream(String path)

  • / 开头,则:不被允许 ———— 即:path不能以/开头
URL url = ClassLoader.getSystemResource("/") //【X,错误示范】
//null

ClassLoader.getSystemResourceAsStream("/") //【X,错误示范】
//null

ClassLoader.getSystemClassLoader().getResource("/")//【X,错误示范】
//null

URL url = Thread.currentThread().getContextClassLoader().getResource("/"); //【X,错误示范】
//null

URL url = XXServiceBizApplication.class.getClassLoader().getResource("/"); //【X,错误示范】
//null

  • 不以 / 开头时,则:默认从ClassPath根下获取
URL url = ClassLoader.getSystemResource("")
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/

ClassLoader.getSystemClassLoader().getResource("")
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/

URL url = XXServiceBizApplication.class.getClassLoader().getResource("");
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/

URL url = XXServiceBizApplication.class.getClassLoader().getResource("./i18n/messages_en_US.properties");
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/i18n/messages_en_US.properties


URL url = Thread.currentThread().getContextClassLoader().getResource("i18n/messages_en_US.properties"); 
///E:/source_code/xxx/xx_service/xx-service-biz/target/classes/i18n/messages_en_US.properties


InputStream inputStream = XXServiceBizApplication.class.getClassLoader().getResourceAsStream("i18n/messages_en_US.properties");
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("i18n/messages_en_US.properties");

X 参考文献

posted @   千千寰宇  阅读(440)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示