property文件配置项目
TestProperties.java
- Eclipse中右键src新建config的Folder
- 在config中新建xxx.properties的配置文件
- 参考图形界面中的坦克大战注释
- 对应于马士兵老师坦克大战图片版2.9_1–2.9_2
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Properties;
public class TestProperties extends Frame{
int initCount;
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.drawString("" + initCount, 100, 100);
g.setColor(c);
}
public void launchFrame() {
initCount = Integer.parseInt(PropertyMgr.getProperty("initCount"));
setLocation(100, 100);
setSize(800, 600);
setResizable(false);
setTitle("TestProperties");
setBackground(Color.green);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
new Thread(new PaintThread()).start();
}
public static void main(String[] args) {
TestProperties tp = new TestProperties();
tp.launchFrame();
}
private class PaintThread extends Thread {
public void run() {
while(true) {
repaint();
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
PropertyMgr.java
import java.io.IOException;
import java.util.Properties;
public class PropertyMgr {
static Properties props = new Properties();
static {
try {
props.load(PropertyMgr.class.getClassLoader().getResourceAsStream("config/test.properties"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
private PropertyMgr() {};
}
test.properties
- 等号左右不要有空格,左边是key,右边是value
- 下一个键值对换行写
initCount=10