我尝试加载属性文件,如下所示
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);
我也尝试将所有内容更改为公共静态,但似乎无法加载属性文件,因为 reader 似乎无法识别。
答案 0 :(得分:1)
这不是在类成员上调用函数的有效语法。您可以使用static
初始化块。并且FileReader
构造函数也可以抛出Exception
。您可以将初始化移动到同一个块中。像,
private static FileReader reader;
private static Properties properties = new Properties();
static {
try {
reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties");
properties.load(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:1)
如上面的Elliott所共享,您需要从静态块调用load函数。如果从静态块中调用它,则必须注意在静态块中初始化用户名和密码(以及任何其他依赖项)。或者另一种选择是在主函数的开头初始化它们:
静态阻止:
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();
}
......
......
......