gpt4 book ai didi

java - 无法在java中加载属性文件

转载 作者:行者123 更新时间:2023-12-02 02:14:32 25 4
gpt4 key购买 nike

我尝试加载如下属性文件,

public class A_Main {

private static FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties");

private static Properties properties = new Properties();
private static properties.load(reader);

public static String UserName = properties.getProperty("lists.user");
public static String Passwd = properties.getProperty("lists.password");
......
......
......
public static void main(String[] args) throws IOException {

Configuration_Report conf = new Configuration_Report();
try {
conf.conf_report(UserName, Passwd);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......

但是,在 Eclipse 中,它在下面的代码下标记了一个错误,

private static properties.load(reader);

我也尝试将所有内容更改为公共(public)静态,但是似乎无法加载属性文件,因为阅读器似乎无法识别。

最佳答案

正如 Elliott 上面分享的那样,您需要从静态 block 中调用加载函数。如果您从静态 block 调用它,那么您必须注意在静态 block 中初始化用户名和密码(以及任何其他依赖项)。或者另一种选择是在主函数开始时初始化它们:

静态 block :

public class A_Main {

private static Properties properties = new Properties();

public static String UserName = null;
public static String Passwd = null;

static{
try (FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties"))
{
properties.load(reader);
UserName = properties.getProperty("lists.user");
Passwd = properties.getProperty("lists.password");
} catch (IOException e) {
e.printStackTrace();
}

}
......
......
......
public static void main(String[] args) throws IOException {

Configuration_Report conf = new Configuration_Report();
try {
conf.conf_report(UserName, Passwd);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......

内部主要功能:

public class A_Main {

private static Properties properties = new Properties();
public static String UserName = null;
public static String Passwd = null;

......
......
......
public static void main(String[] args) throws IOException {
try (FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties"))
{
properties.load(reader);
UserName = properties.getProperty("lists.user");
Passwd = properties.getProperty("lists.password");
Configuration_Report conf = new Configuration_Report();
conf.conf_report(UserName, Passwd);
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......

关于java - 无法在java中加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49478002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com