package com.day06;
/**
* @author anyan
* @date 2021/5/25-15:50
*/
/*
如何獲取文件的絕對路徑?以下方式有一個前提:文件必須在類路徑,即src路徑下。
//
*/
public class AboutPath {
public static void main(String[] args) {
//Thread.currentThread() 當前線程
//get.ContextClassLoader() 類加載器
//getResource() 獲取文件,此文件必須位於類路徑下,即src目錄下.默認從類路徑下作為起點
//getPath() 獲取絕對路徑
//總結:通過當前線程下的類加載器下的獲取源文件方法獲取文件的絕對路徑
/* String path=Thread.currentThread().getContextClassLoader().getResource("classinfor.properties").getPath();
System.out.println(path);*/
String path1=Thread.currentThread().getContextClassLoader().getResource("myfile.properties").getPath();
System.out.println(path1);
String path2=Thread.currentThread().getContextClassLoader().getResource("com/day06/myfile.text").getPath();
System.out.println(path2);
}
}
/*
方法2
*/
package com.day06;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author anyan
* @date 2021/5/25-17:02
*/
/*
讀取文件時以流的形式返回
*/
public class PathTest {
public static void main(String[] args) throws IOException {
InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("com/day06/classinfor.properties");
Properties pro=new Properties();
pro.load(in);
String s1=pro.getProperty("userName");
System.out.println(s1);
}
}