我正在尝试从属性文件中读取值并且
当我尝试运行这个程序时
其输出为
空
import java.io.FileInputStream;
import java.util.Properties;
public class JavaApplication1 {
final private static String osName = System.getProperty("os.name");
static final Properties configFile = new Properties() {
{
try {
configFile.load(new FileInputStream("config.properties"));
} catch (Exception e) {
}
}
};
private static String DIR = osName.equals("Linux") ? configFile.getProperty("tempDirForLinux") : configFile.getProperty("tempDirForWindows");
public static void main(String[] args) {
System.out.println(DIR);
}
}
最佳答案
在您的示例中有点奇怪的部分是您创建一个匿名 Properties 类,然后在初始化语句中将属性加载到同一类中。我不确定这是如何工作的(我猜不会)
这可能正是您想要的
public class JavaApplication1 {
final private static String osName = System.getProperty("os.name");
static final Properties configFile = new Properties();
static {
try {
configFile.load(new FileInputStream("config.properties"));
} catch (Exception e) {
e.printStackTrace();
}
};
private static String DIR = osName.equals("Linux") ? configFile.getProperty("tempDirForLinux") : configFile.getProperty("tempDirForWindows");
public static void main(String[] args) throws IOException {
System.out.println(DIR);
}
}
关于java - 属性文件返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10270480/