Java 怎么根据key删除properties文件中的属性

2025-05-17 11:43:00
推荐回答(3个)
回答(1):

java 根据key删除properties文件中的属性可以使用文件流先加载,然后读取key,修改制定的值,如下代码:

    /**
     *写入properties信息
     * @param parameterName 配置文件属性名
     * @param parameterValue 需要写入的配置文件的信息
     */
    public static void writeProperties(String parameterName,
                                       String parameterValue) throws
        IOException {
        Properties prop = new Properties();
        try {
            InputStream fis = new FileInputStream(ctxRealPath);
            //从输入流中读取属性列表(键和元素对)
            prop.load(fis);
            //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
            //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
            OutputStream fos = new FileOutputStream(ctxRealPath);
            prop.put(parameterName, parameterValue);
            //以适合使用 load 方法加载到 Properties 表中的格式,
            //将此 Properties 表中的属性列表(键和元素对)写入输出流
            prop.store(fos, " Update '" + parameterName + "' value");
            setLastUpdateBalanceStat(parameterValue);
        }
        catch (IOException e) {
//        Print.print("ConfigInfoError","Visit "+filePath+" for updating "+parameterName+" value error");
            System.err.println("**********************");
            System.err.println("\r\n write BalanceStat configuration failed,please check "+ctxRealPath+" is writer . thank you \n\n");
            System.err.println("**********************");
//            throw e;
        }
    }

调用的时候你只要传入
writeProperties(key2,123456);

回答(2):

	public static void main(String[] args) {
/***
 * test.properties
 * 
 * a=123
 * b=456
 * */
String key = "a";
Properties props = new Properties();
BufferedInputStream fis;
String path = "src/test.properties";
try {
fis = new BufferedInputStream (new FileInputStream(path));
props.load(fis);
props.remove(key);
OutputStream fos = new FileOutputStream(path);
        //将此 Properties 表中的属性列表(键和元素对)写入输出流
props.store(fos, "Delete "+key);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/***
 * test.properties
 * 
 * #Delete a
 * #Fri Apr 24 13:59:59 CST 2015
 * b=456
 * */
}

回答(3):

你没保存啊,执行保存后才有效果