- /**
- * PropertyUtil属性文件读写工具类
- */
- public class PropertyUtil {
- /**
- * 指定property文件
- */
- public static final String PROPERTY_FILE =WindowsUtil.getOSName().equals("Windows XP")? "c:/windows/config.properties":"d:\\config.properties";
- public static final String LOG_FILE = "c:/windows/EcollectLog.properties";
- /**
- * 根据Key 读取Value
- *
- * @param key
- * @return
- */
- public static String readData(String key) {
- Properties props = new Properties();
- try {
- InputStream in = new BufferedInputStream(new FileInputStream(
- PROPERTY_FILE));
- props.load(in);
- in.close();
- String value = props.getProperty(key);
- return value;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- /**
- * 修改或添加键值对 如果key存在,修改 反之,添加。
- *
- * @param key
- * @param value
- */
- public static void writeData(String key, String value) {
- Properties prop = new Properties();
- try {
- File file = new File(PROPERTY_FILE);
- if (!file.exists())
- file.createNewFile();
- InputStream fis = new FileInputStream(file);
- prop.load(fis);
- fis.close();//一定要在修改值之前关闭fis
- OutputStream fos = new FileOutputStream(PROPERTY_FILE);
- prop.setProperty(key, value);
- prop.store(fos, "Update '" + key + "' value");
- fos.close();
- } catch (IOException e) {
- System.err.println("Visit " + PROPERTY_FILE + " for updating "
- + value + " value error");
- }
- }
- /**
- * 获取参数对象
- * @return
- */
- public static Parameter getParameterByFile(){
- Parameter p = null;
- File f = new File(PROPERTY_FILE);
- if(f.exists()){
- p = new Parameter();
- p.setIp(readData("ip"));
- p.setPort(readData("port"));
- p.setLocalFolder(readData("localFolder"));
- p.setLocalFolder2(readData("localFolder2"));
- p.setLocalFolder3(readData("localFolder3"));
- p.setUsername(readData("username"));
- p.setPassword(readData("password"));
- }
- return p;
- }
- public static void main(String[] args) {
- PropertyUtil.writeData("ip", "192.168.1.1");
- PropertyUtil.writeData("port", "21");
- PropertyUtil.writeData("username", "ddb");
- PropertyUtil.writeData("password", "ddd2");
- PropertyUtil.writeData("localFolder", "d:\\dwg");
- }
- }