java如何创建properties
创建 Properties 文件的方法
方法1:使用 java.util.Properties 类
Properties prop = new Properties();
prop.setProperty("key1", "value1");
prop.setProperty("key2", "value2");
try (OutputStream output = new FileOutputStream("config.properties")) {
prop.store(output, "Comments here");
} catch (IOException e) {
e.printStackTrace();
}
方法2:通过输入流读取现有文件
Properties prop = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
方法3:使用资源文件(ClassLoader)
Properties prop = new Properties();
try (InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties")) {
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
文件格式示例
生成的 config.properties 文件内容如下:

#Comments here
key1=value1
key2=value2
注意事项
- 键值对默认以 ISO 8859-1 字符编码存储
- 中文等非ASCII字符需使用 Unicode 转义(如
\u4E2D\u6587) - 路径建议使用相对路径或完整绝对路径






