java獲取各種路徑的基本方法
更新時(shí)間:2016年10月11日 08:39:55 作者:浪漫逆風(fēng)
這篇文章主要為大家詳細(xì)介紹了java獲取各種路徑的基本方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了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 { /** * 獲取當(dāng)前類所在的工程路徑 */ @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); } /** * 獲取當(dāng)前類的絕對路徑 */ @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); } /** * 獲取當(dāng)前類所在的工程路徑,兩種方法皆可 * * @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")); } /** * 獲取當(dāng)前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(); // 使用這種方式可以獲取文件對應(yīng)的輸出流 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(inputStream); File file = new File(url.getPath()); System.out.println(properties.get("jdbc.driverClassName")); } }
下面賦上代碼對應(yīng)的文件路徑
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Intellj?idea新建的java源文件夾不是藍(lán)色的圖文解決辦法
idea打開java項(xiàng)目后新建的模塊中,java文件夾需要變成藍(lán)色,這篇文章主要給大家介紹了關(guān)于Intellj?idea新建的java源文件夾不是藍(lán)色的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02Java語言實(shí)現(xiàn)基數(shù)排序代碼分享
這篇文章主要介紹了Java語言實(shí)現(xiàn)基數(shù)排序代碼分享,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12Java實(shí)現(xiàn)WORD和PDF互相轉(zhuǎn)換以及數(shù)據(jù)填充示例
本文介紹了如何使用Java實(shí)現(xiàn)WORD和PDF的互轉(zhuǎn)以及數(shù)據(jù)填充功能,通過導(dǎo)入Aspose庫并使用其工具類,可以輕松實(shí)現(xiàn)WORD和PDF模板的填充和轉(zhuǎn)換,需要的朋友可以參考下2025-02-02SpringBoot訪問MongoDB數(shù)據(jù)庫的兩種方式
MongoDB是一種非關(guān)系型數(shù)據(jù)庫,通過文檔存儲數(shù)據(jù),適用于大規(guī)模數(shù)據(jù)存儲和高并發(fā)訪問,這篇文章主要介紹了SpringBoot訪問MongoDB數(shù)據(jù)庫的兩種方式,感興趣想要詳細(xì)了解可以參考下文2023-05-05