java中擷取路徑的幾種基本的方法,java擷取路徑幾種
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")); }}
下面賦上代碼對應的檔案路徑