我一直在开发一个游戏(我的第一个游戏之一^^),但在导入属性时遇到了问题。下面我发布了所有相关文件和我遇到的问题 - 如果有人知道我去了哪里以及我可以修复它,我将非常感激:)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~ 这是我的主类(目前仅用于测试)
package game;
public class Main {
//Setup
static Settings settings = null;
public static void main(String args[]){
System.out.println("Main Started");
settings = new Settings();
String test = settings.getProperty("test");
String hello = settings.getProperty("hello");
System.out.println("Test: " + test);
System.out.println("Hello: " + hello);
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~
这是调用时加载设置的设置类。
package game;
//Imports
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
public class Settings {
Properties config = new Properties();
InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties");
public Settings(){
System.out.println();
}
public String getProperty(String key){
String value = config.getProperty(key);
return value;
}
public int getValue(String key){
int value = Integer.parseInt(config.getProperty(key));
return value;
}
public void close(){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~
这是属性文件(.properties)
#Test Strings
test = "this is a test"
hello = "Hello, World."
#Resolution Settings
width = 800
height = 600
scale = 1
#Cars
speed = 1
cars = 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~
这是控制台,返回null
Main Started
Test: null
Hello: null
感谢您的阅读!我希望你能帮忙:)
最佳答案
在初始化 Settings
对象时,您应该为 config
和 input
正确加载资源,例如:
public class Settings {
Properties config = new Properties();
InputStream input = null;
public Settings(){
input = getClass().getClassLoader().getResourceAsStream("config.properties");
// or use input = new FileInputStream("config.properties");
config.load(input)
}
.... // other of your functions
}
而且我认为,属性的文件名应该成为一个参数,以增强Settings
类的灵 active ,例如:
public Settings(String filename){
input = getClass().getClassLoader().getResourceAsStream(filename);
// or use input = new FileInputStream(filename)
config.load(input)
}
并在主要部分:
public static void main(String args[]){
System.out.println("Main Started");
settings = new Settings("config.properties");
String test = settings.getProperty("test");
String hello = settings.getProperty("hello");
// say you have another properties named config2.properties to read
Settings another_settings = new Settings("config2.properties");
String xxx = settings.getProperty("xxx");
String yyy = settings.getProperty("yyy");
}
关于java - 无法读取java中的配置值(null返回的不是值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223150/