java獲取各種路徑的基本方法
更新時間:2016年10月11日 08:39:55 作者:浪漫逆風
這篇文章主要為大家詳細介紹了java獲取各種路徑的基本方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java獲取不同路徑的方法,供大家參考,具體內(nèi)容如下
package com.ygh.blog.realpath;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
/**
* 獲取java下面的路徑的演示
*/
import org.junit.Test;
public class RealPathTest {
/**
* 獲取當前類所在的工程路徑
*/
@Test
public void fun1() {
File file = new File(this.getClass().getResource("/").getPath());
// D:\project\taotaoshop\src\blog-mybatis1\target\test-classes
System.out.println(file);
}
/**
* 獲取當前類的絕對路徑
*/
@Test
public void fun2() {
File file = new File(this.getClass().getResource("").getPath());
// D:\project\taotaoshop\src\blog-mybatis1\target\test-classes\com\ygh\blog\realpath
System.out.println(file);
}
/**
* 獲取當前類所在的工程路徑,兩種方法皆可
*
* @throws IOException
*/
@Test
public void fun3() throws IOException {
File file = new File("");
String path = file.getCanonicalPath();
// D:\project\taotaoshop\src\blog-mybatis1
System.out.println(path);
// D:\project\taotaoshop\src\blog-mybatis1
System.out.println(System.getProperty("user.dir"));
}
/**
* 獲取當前src下面的文件的路徑
*/
@Test
public void fun4() {
URL url = this.getClass().getClassLoader().getResource("jdbc.properties");
System.out.println(url);
}
/**
* 獲取其他源碼包下面的文件路徑
*/
@Test
public void fun5() {
// 使用這種方法可以獲取路徑
URL url = this.getClass().getClassLoader().getResource("test2.txt");
// file:/D:/project/taotaoshop/src/blog-mybatis1/target/classes/test.txt
System.out.println(url);
}
@Test
public void fun6() throws Exception {
URL url = this.getClass().getClassLoader().getResource("test2.txt");
System.out.println(url.getPath());
Properties properties = new Properties();
// 使用這種方式可以獲取文件對應的輸出流
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(inputStream);
File file = new File(url.getPath());
System.out.println(properties.get("jdbc.driverClassName"));
}
}
下面賦上代碼對應的文件路徑

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot 監(jiān)聽Redis鍵過期事件(過期監(jiān)聽)
Redis鍵過期事件是SpringBoot中常用的緩存失效通知方式,通過配置可以監(jiān)聽特定鍵的過期事件,具有一定的參考價值,感興趣的可以了解一下2024-12-12
詳談StringUtils3之StringUtils.isEmpty()和StringUtils.isB的區(qū)別
這篇文章主要介紹了詳談StringUtils3之StringUtils.isEmpty()和StringUtils.isB的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
使用Spring MVC實現(xiàn)雙向數(shù)據(jù)綁定
Spring MVC是一個廣泛用于構建Java Web應用程序的框架,它提供了眾多功能,包括雙向數(shù)據(jù)綁定,在這篇文章中,我們將向Java新手介紹如何使用Spring MVC實現(xiàn)雙向數(shù)據(jù)綁定,以及為什么這個特性如此重要,需要的朋友可以參考下2024-01-01
java springboot郵箱找回密碼功能的實現(xiàn)講解
這篇文章主要介紹了java springboot郵箱找回密碼功能的實現(xiàn)講解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
Spring+MyBatis多數(shù)據(jù)源配置實現(xiàn)示例
本篇文章主要介紹了Spring+MyBatis多數(shù)據(jù)源配置實現(xiàn)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01

