杰瑞科技汇

Java properties文件如何读写?

Properties 文件是什么?

Properties 文件是一种纯文本文件,通常以 .properties 作为后缀名,它的结构非常简单:

Java properties文件如何读写?-图1
(图片来源网络,侵删)
  • 键值对:每行一个键值对,格式为 key = valuekey:value
  • 注释:以 或 开头的行被视为注释,会被忽略。
  • 编码:通常使用 ISO-8859-1 (Latin-1) 编码,如果需要存储非 ASCII 字符(如中文),需要进行转义或使用 Java 9+ 引入的 UTF-8 支持。

示例 config.properties 文件:

# Database Configuration
db.url=jdbc:mysql://localhost:3306/mydb
db.username=admin
db.password=secret123
# Application Settings
app.name=My Awesome App
app.version=1.0.0
app.debug=true

读取 Properties 文件

读取 Properties 文件主要有两种常用方法:

使用 ClassLoader.getResourceAsStream() (推荐)

这种方法更健壮,因为它不依赖于文件的绝对路径,而是从类路径(Classpath)中加载资源,无论是从 IDE 运行还是从 JAR 包运行,都能正常工作。

核心步骤:

Java properties文件如何读写?-图2
(图片来源网络,侵删)
  1. 获取当前线程的上下文类加载器或当前类的类加载器。
  2. 使用 getResourceAsStream() 方法获取资源文件的输入流。
  3. 创建 Properties 对象。
  4. 调用 load(InputStream) 方法加载输入流。
  5. 使用 getProperty(String key)get(String key) 方法获取属性值。

代码示例:

假设 config.properties 文件位于 src/main/resources 目录下。

import java.io.InputStream;
import java.util.Properties;
public class PropertiesReader {
    public static void main(String[] args) {
        // 1. 创建 Properties 对象
        Properties props = new Properties();
        // 使用 try-with-resources 确保 InputStream 自动关闭
        try (InputStream input = PropertiesReader.class.getClassLoader().getResourceAsStream("config.properties")) {
            // 2. 检查输入流是否为空(文件未找到)
            if (input == null) {
                System.out.println("Sorry, unable to find config.properties");
                return;
            }
            // 3. 加载 properties 文件
            props.load(input);
            // 4. 读取属性值
            String dbUrl = props.getProperty("db.url");
            String username = props.getProperty("db.username");
            String password = props.getProperty("db.password");
            String appName = props.getProperty("app.name", "Default App Name"); // 提供默认值
            boolean isDebug = Boolean.parseBoolean(props.getProperty("app.debug"));
            // 5. 打印读取到的值
            System.out.println("Database URL: " + dbUrl);
            System.out.println("Username: " + username);
            System.out.println("Password: " + password);
            System.out.println("App Name: " + appName);
            System.out.println("Debug Mode: " + isDebug);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

使用 FileInputStream (基于文件路径)

这种方法直接从文件系统读取,需要提供文件的绝对路径或相对于当前工作目录的路径,在将应用打包成 JAR 后,这种方式可能会因为路径问题而失败。

代码示例:

Java properties文件如何读写?-图3
(图片来源网络,侵删)
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesFileReader {
    public static void main(String[] args) {
        Properties props = new Properties();
        // 假设文件在项目根目录下
        String path = "config.properties";
        try (InputStream input = new FileInputStream(path)) {
            props.load(input);
            // 读取和打印属性...
            System.out.println("App Name: " + props.getProperty("app.name"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

写入 Properties 文件

写入操作通常使用 FileOutputStream,你可以创建一个新的 .properties 文件,或者更新一个已存在的文件。

核心步骤:

  1. 创建 Properties 对象。
  2. 使用 setProperty(String key, String value) 方法设置键值对。
  3. 创建 FileOutputStream 指定输出文件路径。
  4. 调用 store(OutputStream out, String comments) 方法将属性列表写入输出流。
    • comments 参数是写入文件顶部的注释,可以为 null
    • 注意store 方法会自动处理字符的转义,并生成符合 .properties 格式的文件。

代码示例:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class PropertiesWriter {
    public static void main(String[] args) {
        Properties props = new Properties();
        // 1. 设置属性
        props.setProperty("server.host", "localhost");
        props.setProperty("server.port", "8080");
        props.setProperty("logging.level", "INFO");
        props.setProperty("feature.new", "true");
        // 文件输出路径
        String path = "new_config.properties";
        // 使用 try-with-resources 确保 OutputStream 自动关闭
        try (OutputStream output = new FileOutputStream(path)) {
            // 2. 将属性写入文件
            // 第二个参数是文件顶部的注释
            props.store(output, "Application Configuration File");
            System.out.println("Properties file saved to: " + path);
        } catch (IOException io) {
            io.printStackTrace();
        }
    }
}

生成的 new_config.properties 文件内容:

#Application Configuration File
#Mon Nov 20 10:30:00 CST 2025
feature.new=true
logging.level=INFO
server.port=8080
server.host=localhost

高级用法与最佳实践

处理中文等非 ASCII 字符

标准的 Properties.load(InputStream) 默认使用 ISO-8859-1 编码,直接写入中文会导致乱码,为了解决这个问题,需要手动指定字符集。

读取中文(Java 9+ 更简单):

Java 9 及以上版本:

Properties.load(Reader) 方法可以直接使用 InputStreamReader 指定 UTF-8 编码。

// Java 9+
try (InputStream input = ...;
     Reader reader = new InputStreamReader(input, "UTF-8")) {
    props.load(reader);
}

Java 8 及以下版本:

需要使用 java.util.Properties 的一个“变通”方法,因为它没有直接提供带字符集的 load 方法。

// Java 8
try (InputStream input = ...;
     Reader reader = new InputStreamReader(input, "UTF-8")) {
    props.load(reader);
}

写入中文:

同样,使用 OutputStreamWriter 指定 UTF-8 编码。

try (OutputStream output = ...;
     Writer writer = new OutputStreamWriter(output, "UTF-8")) {
    props.store(writer, "Comments with Chinese: 中文");
}

在 Maven/Gradle 项目中放置 Properties 文件

  • Maven: 将文件放在 src/main/resources 目录下,当项目打包时(如 jarwar),Maven 会自动将这个目录下的所有文件复制到最终输出文件的根目录下,使用 getClassLoader().getResourceAsStream("config.properties") 可以直接访问。
  • Gradle: 同样,将文件放在 src/main/resources 目录下。

获取属性时的默认值

getProperty(String key) 方法如果找不到对应的 key,会返回 null,为了避免 NullPointerException,可以提供一个默认值:

String port = props.getProperty("server.port", "8080"); // server.port 不存在,则返回 "8080"

操作 推荐方法 关键代码 适用场景
读取 ClassLoader.getResourceAsStream() props.load(input) 生产环境首选,与项目打包方式无关,健壮性高。
读取 FileInputStream props.load(new FileInputStream(path)) 快速测试,或文件位置固定且不在类路径下时。
写入 FileOutputStream props.store(output, comments) 创建或更新配置文件。
处理中文 InputStreamReader / OutputStreamWriter new InputStreamReader(input, "UTF-8") 必须使用,以避免乱码。

掌握 Properties 类的读写是 Java 开发中一项非常基础且重要的技能,希望这份详细的讲解能帮助你完全理解它。

分享:
扫描分享到社交APP
上一篇
下一篇