public static void main(String[] args) throws IOException {
System.out.println(new File(".").getAbsolutePath());
Properties pro = new Properties();
//相對(duì)路徑
//InputStream input = new BufferedInputStream(new FileInputStream("src/text.properties"));
//絕對(duì)路徑
InputStream input = new BufferedInputStream(new FileInputStream("D:/stsworkspace/utils/src/text.properties"));
pro.load(input);
Iterator<String> it=pro.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
System.out.println(key+":"+pro.getProperty(key));
}
input.close();
}
相對(duì)路徑
java IO會(huì)默認(rèn)定位到文件的根目錄即:D:/stsworkspace/utils,以此的相對(duì)路徑來(lái)找到text.properties這個(gè)文件下面就是src/text.properties。
那么JVM會(huì)找到路徑D:/stsworkspace/utils/src/text.properties,這里為什么src/text.properties前面沒(méi)有"/",?
"(無(wú))","/","./","../"區(qū)別
1.(無(wú))開(kāi)頭表示當(dāng)前目錄下的
2.(/)開(kāi)頭的目錄表示該目錄為根目錄的一個(gè)子目錄
3.(./)開(kāi)頭的目錄表示該目錄為當(dāng)前目錄(當(dāng)前目錄所在的目錄)的一個(gè)子目錄
4.(../)開(kāi)頭的目錄表示該目錄為當(dāng)前目錄的父目錄
絕對(duì)路徑
文件真實(shí)存的路徑,本地硬盤中路徑
web開(kāi)發(fā)中的使用
在Web開(kāi)發(fā)中盡量使用絕對(duì)路徑,前一段路徑無(wú)論是用的Windows或Linux開(kāi)發(fā),都可以利用 ServletActionContext.getServletContext().getRealPath(path); 來(lái)獲取!
案例
在uitls類中讀取該路徑下的文件
public class ConfigManager {
private static final Logger logger = LoggerFactory.getLogger(ConfigManager.class);
private static ConfigManager configManager;
// 讀取屬性文件
private static Properties properties;
/**
* 在構(gòu)造器中初始化讀取properties文件
*/
private ConfigManager() {
String configManager = this.getClass().getResource("").getPath();
logger.info("configManager:-------" + configManager);
String path = configManager.substring(0, configManager.indexOf("WEB-INF")) + "WEB-INF/db.properties";
properties = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(path));
//InputStream in = new BufferedInputStream(new FileInputStream("src/main/webapp/WEB-INF/db.properties"));
properties.load(in);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
在servelet中讀取文件
方法一:
String path = getServletContext().getRealPath("");
Properties config = new Properties();
InputStream in = new FileInputStream(path+"/WEB-INF/db.properties");
config.load(in);
方法二:
Properties config = new Properties();
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/db.properties");
config.load(in);