java怎么读取properties配置文件

31次阅读
没有评论

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

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

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesReader {public static void main(String[] args) {Properties properties = new Properties();
try {
// 读取配置文件
FileInputStream fis = new FileInputStream("config.properties");
properties.load(fis);
// 获取配置项的值
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("Username:" + username);
System.out.println("Password:" + password);
fis.close();} catch (IOException e) {e.printStackTrace();
}
}
}

在上面的示例中,假设我们有一个名为 config.properties 的配置文件,内容如下:

username=admin
password=123456

通过 FileInputStream 类加载文件流,并使用 load() 方法将配置文件加载到 Properties 对象中。然后,可以使用 getProperty() 方法获取配置项的值。
请注意,需要提供正确的配置文件路径。如果配置文件位于项目的根目录下,则可以使用相对路径,如上述示例中的"config.properties"。如果配置文件位于其他位置,需要指定完整的文件路径。

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

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