java - 更改Java项目的属性文件

标签 java properties-file

我需要对 Java 项目中的 .properties 文件进行更改。随后将其部署为 jar 并由其他 Java 项目使用。但根据this ,我发现我们不应该直接进行更改,而是创建一个新对象。我们应该在哪里创建新对象以及如何确保其更改可见?

最佳答案

是的,如果您的属性文件位于 jar 内,那么您将无法直接更改该属性文件,因为它已打包并压缩在存档中。相反,您可以创建/更改放置在驱动器上的文件并读取它,我使用 "user.home" 作为示例,您可以根据需要更改它,下面是相同的代码:

package com.test.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertyFileReader {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(PropertyFileReader.class);

    private static Properties properties;
    private static final String APPLICATION_PROPERTIES = "application.properties";
    private static final String workingDir = System.getProperty("user.home");
    private static File file = new File(workingDir, APPLICATION_PROPERTIES);
    static {
        properties = new Properties();
    }

    public static void main(String[] args) {
        write("hello", "2");
        System.out.println(read("hello"));
    }

    public static String read(final String propertyName) {
        try (InputStream input = new FileInputStream(file)) {
            properties.load(input);
        } catch (IOException ex) {
            LOGGER.error("Error occurred while reading property from file : ",
                    ex);
        }
        return properties.getProperty(propertyName);
    }

    public static void write(final String propertName,
            final String propertyValue) {
        try (OutputStream output = new FileOutputStream(file)) {
            properties.setProperty(propertName, propertyValue);
            properties.store(output, null);
        } catch (IOException io) {
            LOGGER.error("Error occurred while writing property to file : ", io);
        }
    }
}

关于java - 更改Java项目的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246391/

相关文章:

java - Spring Roo 和读取属性文件

java - Spring Boot 默认属性编码更改?

java - 进度对话框阻止内容 View 切换?

java - Apache Taglibs 和 Glassfish JSTL 的实现之间的区别?

java - 将 Activity 1 中的值传递给 Activity 2 进行计算并显示结果

spring - 原始类型的属性不允许使用“lateinit”修饰符 - Kotlin

java - Spring 3.0如何实现脚手架

java - 为什么负输入在 for 循环中不起作用

java - 除非我 fork JVM,否则在 ant 下运行的代码找不到属性文件

maven - 如何在属性文件中写入相对路径