我需要对 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/