我需要在Java项目中对.properties
文件进行更改。稍后将其部署为jar
并由其他Java项目使用。但根据this,我发现我们不应该直接进行更改而是创建一个新对象。我们应该在哪里创建新对象,以及如何确保其更改可见?
答案 0 :(得分:1)
是的,如果您的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);
}
}
}
在jar中,那么您将无法直接更改该属性文件,因为它已打包并压缩到存档中。相反,您可以创建/更改放置在驱动器上的文件并阅读它,我使用" user.home" 作为示例,您可以根据需要更改它,下面是代码相同:
getrusage