可以使用 Properties 类的 'load()' 方法将文件中的内容读入到 Properties 对象中。代码示例如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.io.File;

public class FileToProperties {
    public static void main(String[] args) {
        File file = new File('config.properties');
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(properties.getProperty('name'));
    }
}

在上述代码中,首先创建一个 File 对象,表示要读取的配置文件,然后创建一个 Properties 对象。接着,使用 Properties 类的 'load()' 方法将文件中的内容读入到 Properties 对象中。最后,可以通过 'getProperty()' 方法获取配置项的值。

Java 文件转 Properties 对象:完整指南与代码示例

原文地址: https://www.cveoy.top/t/topic/ol8V 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录