配置文件

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

  • 实现工程的所有类共用同一个property文件
import java.io.IOException;
import java.util.Properties;
public class PropertyMgr {
    static Properties props = new Properties();
    static {//单例模式,内存中只有一个props就行了,以后就直接从内存中拿数据,不用从硬盘取了
        try {
            props.load(PropertyMgr.class.getClassLoader().getResourceAsStream("config/test.properties"));//这里记得要加config/否则会出现空指针错误
            //静态方法没有对象,所以写类名.class.getClassLoader(),非静态方法中可以写this.getClassLoader().
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }//上面这几行不能写到下面的函数里,否则每次调用都会取硬盘load数据
    public static String getProperty(String key) {
        return props.getProperty(key);
    }
    private PropertyMgr() {};//构造方法写成私有,其他类不能new这个类,只能调用静态方法
}

test.properties

  • 等号左右不要有空格,左边是key,右边是value
  • 下一个键值对换行写
initCount=10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值