JavaWeb項目區別於普通Java項目,它會在服務器中編譯,編譯後的文件會存在服務器下的Webapps文件夾中,因此,在項目發佈後,修改.properties文件,路徑成了問題。
InputStream input =PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
像上面的加載方式,修改.properties文件後,會將config.properties文件加載到內存中,在下次需要讀取時直接從內存中獲取文件信息,而不是再次讀取。因此要轉變輸入流獲取方式。
String path=PropertiesUtil.class.getClassLoader().getResource(file).getPath();
InputStream input=new FileInputStream(path);
下面是我封裝的工具類,請多指教。
package com.yc.utils;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 加載 .properties 文件工具類
* @author S3
*
*/
public class PropertiesUtil {
public static Map<String, String> readProperties(String file) throws IOException{
Map<String, String> map=new HashMap<String,String>();
String path=PropertiesUtil.class.getClassLoader().getResource(file).getPath();
InputStream input=new FileInputStream(path);
BufferedReader bf=new BufferedReader(new InputStreamReader(input));
Properties p = new Properties();
try {
p.load(bf);
} catch (IOException e) {
e.printStackTrace();
}finally{
input.close();
bf.close();
}
if(p.getProperty("name")!=null && p.getProperty("tel")!=null){
map.put("name", p.getProperty("name"));
map.put("tel", p.getProperty("tel"));
return map;
}
return null;
}
//修改方法
public static void writeProperties(String file,String name,String tel) throws IOException{
FileOutputStream fos = null;
try {
fos=new FileOutputStream(PropertiesUtil.class.getClassLoader().getResource(file).getPath());
Properties p =new Properties();
p.setProperty("name", name);
p.setProperty("tel", tel);
p.store(fos,"保存");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
fos.close();
}
}
//測試類
public static void main(String[] args) throws IOException {
System.out.println(readProperties("admin.properties"));
writeProperties("admin.properties", "a", "110");
}
}