Properties读写操作

不是很完美,懒得改


import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.Properties;

public class FileReader {
    /**
     * 获取绝对路径
     * @param relativePath 相对路径
     * @return
     */
    public static String getAbPath(String relativePath){
        ClassLoader classLoader = FileReader.class.getClassLoader();
        return classLoader.getResource(relativePath).getPath();
    }

    public static Properties read(String path) throws IOException {
        ClassLoader classLoader = FileReader.class.getClassLoader();
        String s = classLoader.getResource(path).getPath();
        assert StringUtils.isNotEmpty(s) && new File(s).exists();
        InputStream is = classLoader.getResourceAsStream(path);
        Properties props = new Properties();
        props.load(new BufferedReader(new InputStreamReader(is)));
        return props;
    }

    /**
     * 更新参数
     * @param relativePath 相对路径
     * @param value  {key,value}
     * @return
     */
    public static boolean updateProperties(String relativePath, String[] value) {
        FileOutputStream fileOutputStream = null;
        try {
            Properties properties = read(relativePath);
            String key = value[0];
            String val = value[1];
            properties.setProperty(key, val);
            String abPath = getAbPath(relativePath);
            fileOutputStream = new FileOutputStream(abPath);
            properties.store(fileOutputStream, "save success");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
posted @ 2021-04-08 16:31  fly_bk  阅读(80)  评论(0)    收藏  举报