java小型数据存储,资源文件读写示例

/*
     * 功能描述:读取资源文件的一个key对应的值
     * @param key 资源文件中对应的key;例如:com.cn.test
     * @param file_path 资源文件的路径,可以为绝对路径;例如:/test.properties
     */
    private static String readProperties(String key, String file_path) {
        Properties props = new Properties();

        InputStream inStream = Main.class.getResourceAsStream(file_path);

        try {
            props.load(inStream);
            inStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return props.getProperty(key);
    }

    /*
     * 功能描述:向资源文件中写入数据,注意资源文件一定要放到src跟目录哦
     * @param key 资源文件中对应的key;例如:com.cn.test
     * @param value 资源文件中key对应的value;
     * @param file_name 注意:资源文件一定要放到src跟目录哦;例如:test.properties
     */
    public static void saveFile(String key, String value, String file_name) {
        String filePath = Main.class.getResource("/").getPath() + file_name;
        File file = new File(filePath);
        InputStream fis = null;
        OutputStream outputFile = null;
        Properties props = new Properties();
        try {
            fis = new FileInputStream(filePath);
            // 从输入流中读取属性列表(键和元素对)
            props.load(fis);
            outputFile = new FileOutputStream(file);
            props.setProperty(key, value);
            // 将此 Properties 表中的属性列表(键和元素对)写入输出流
            props.store(outputFile, "Update '" + value + "' value");
            outputFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值