前提:配置文件的设置
因为我们在配置文件中,有可能使用到汉字,那么我们就应该避免在读取数据时出现乱码,那么我们就需要调制好环境

Properties Files文件,仅仅从名字上看,就知道它是针对properties文件的,那么我们可以根据自己的需要设置编码方式,以及建议将它勾选上
方式一:使用java.util.Properties读取

@Test
public void test4() throws IOException {
Properties properties = new Properties();
FileInputStream fis = new FileInputStream("jdbc.properties");
properties.load(fis);
System.out.println(properties.getProperty("name"));
System.out.println(properties.getProperty("age"));
}

因为我们使用的是单例测试模式,那么此时的jdbc.properties文件应该放在当前module的目录之下
方式二:使用类加载器

@Test
public void test4() throws IOException {
Properties properties = new Properties();
InputStream systemResourceAsStream = ClassLoader.getSystemResourceAsStream("jdbc1.properties");
properties.load(systemResourceAsStream);
System.out.println(properties.getProperty("name"));
System.out.println(properties.getProperty("age"));
}

此时的jdbc1.properties应该放在src目录下。而且在实际开发中,我们也会偏向于第二种。
本文介绍了在Java中读取配置文件的两种方法:一是使用java.util.Properties,需确保配置文件位于模块目录下;二是利用类加载器,适用于配置文件放在src目录下的情况。在处理包含汉字的配置文件时,注意防止乱码问题。
199

被折叠的 条评论
为什么被折叠?



