天天看點

java propertiesutil_java.util.Properties類 學習筆記2

java中的properties檔案是一種配置檔案,主要用于表達配置資訊,檔案類型為*.properties,格式為文本檔案,檔案的内容是格式是”鍵=值”的格式,在properties

檔案中,可以用”#”來作注釋,properties檔案在Java程式設計中用到的地方很多,操作很友善。import java.io.*;

import java.util.Properties;

import javax.servlet.http.*;

import javax.servlet.*;

import javax.servlet.jsp.*;

public class PropertiesUtil {

private String fileName;

private Properties p;

private FileInputStream in;

private FileOutputStream out;

public PropertiesUtil(String fileName) {

this.fileName = fileName;

File file = new File(fileName);

try {

in = new FileInputStream(file);

p = new Properties();

// 載入檔案

p.load(in);

in.close();

} catch (FileNotFoundException e) {

System.err.println("配置檔案config.properties找不到!!");

e.printStackTrace();

} catch (Exception e) {

System.err.println("讀取配置檔案config.properties錯誤!!");

e.printStackTrace();

}

}

public static String getConfigFile(HttpServlet hs) {

return getConfigFile(hs, "config.properties");

}

public static String getConfigFile(HttpServlet hs, String configFileName) {

String configFile = "";

ServletContext sc = hs.getServletContext();

configFile = sc.getRealPath("/" + configFileName);

if (configFile == null || configFile.equals("")) {

configFile = "/" + configFileName;

}

return configFile;

}

public static String getConfigFile(PageContext hs, String configFileName) {

String configFile = "";

ServletContext sc = hs.getServletContext();

configFile = sc.getRealPath("/" + configFileName);

if (configFile == null || configFile.equals("")) {

configFile = "/" + configFileName;

}

return configFile;

}

public void list() {

p.list(System.out);

}

public String getValue(String itemName) {

return p.getProperty(itemName);

}

public String getValue(String itemName, String defaultValue) {

return p.getProperty(itemName, defaultValue);

}

public void setValue(String itemName, String value) {

p.setProperty(itemName, value);

return;

}

public void saveFile(String fileName, String description) throws Exception {

try {

File f = new File(fileName);

out = new FileOutputStream(f);

p.store(out, description);// 儲存檔案

out.close();

} catch (IOException ex) {

throw new Exception("無法儲存指定的配置檔案:" + fileName);

}

}

public void saveFile(String fileName) throws Exception {

saveFile(fileName, "");

}

public void saveFile() throws Exception {

if (fileName.length() == 0)

throw new Exception("需指定儲存的配置檔案名");

saveFile(fileName);

}

public void deleteValue(String value) {

p.remove(value);

}

public static void main(String[] args) {

String file = "D:\\ttt.properties";

PropertiesUtil pu = new PropertiesUtil(file);

pu.list();

}

}