java怎么读取config中的配置文件

31次阅读
没有评论

共计 722 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,可以使用 Properties 类来读取配置文件。下面是一个简单的示例:

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

public class ReadConfigFile {public static void main(String[] args) {Properties properties = new Properties();
        FileInputStream fis = null;

        try {// 加载配置文件
            fis = new FileInputStream("config.properties");
            properties.load(fis);

            // 读取配置项的值
            String value1 = properties.getProperty("key1");
            String value2 = properties.getProperty("key2");

            System.out.println("key1 = " + value1);
            System.out.println("key2 = " + value2);
        } catch (IOException e) {e.printStackTrace();
        } finally {if (fis != null) {try {fis.close();
                } catch (IOException e) {e.printStackTrace();
                }
            }
        }
    }
}

上述代码假设配置文件名为config.properties,文件内容如下:

key1=value1
key2=value2

在文件所在的目录下执行上述代码,就可以读取配置文件中的值了。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计722字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)