对properties文件进行增删改查

对properties文件进行增删改查操作

注:java基础库支持对proterties文件进行增删改查操作,无需引入其他依赖




import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


public class PropertiesUtil {



    /**
     * 获取properties文件
     * @return
     */
    public static Properties getProperties(String path)  {
        Properties properties = new Properties();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(path);
            properties.load(fileInputStream);
            if (fileInputStream!=null){
                fileInputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }



    /**
     * 查询properties文件内容
     */
    public static String toProperties(String path){
        Properties properties = getProperties(path);
        return properties.toString();
    }



    /**
     * 添加properties文件内容
     */
    public static void add(String key,String value,String path) {
        Properties properties = getProperties(path);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path);
            properties.setProperty(key,value);
            properties.store(fileWriter,"UTF-8");
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 对文件进行修改
     * @throws IOException
     */
    public static void update(String key,String value, String path) {
        Properties properties = getProperties(path);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path);
            properties.setProperty(key,value);
            properties.store(fileWriter,"UTF-8");
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 进行属性删除
     * @throws IOException
     */
    public static void delete(String key,String path) {
        Properties properties = getProperties(path);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(path);
            properties.remove(key);
            properties.store(fileWriter,"UTF-8");
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

你可能感兴趣的:(开发语言,java)