java中properties配置文件怎么使用

32次阅读
没有评论

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

在 Java 中,可以使用 java.util.Properties 类来读取和使用配置文件。
首先,创建一个 Properties 对象并加载配置文件。可以使用 Propertiesload()方法来加载配置文件,传入一个 InputStream 对象作为参数。例如,假设配置文件名为config.properties,可以使用以下代码加载该配置文件:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {public static void main(String[] args) {Properties properties = new Properties();
try {properties.load(new FileInputStream("config.properties"));
} catch (IOException e) {e.printStackTrace();
}
// 使用配置文件中的属性值
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("Username:" + username);
System.out.println("Password:" + password);
}
}

然后,可以使用 Properties 对象的 getProperty() 方法根据配置文件中的键获取对应的值。
配置文件 config.properties 的内容如下:

username=admin
password=123456

运行上述代码,将输出:

Username: admin
Password: 123456

这样你就可以在 Java 程序中使用配置文件中的属性值了。

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

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