java 操作properties文件

本文介绍了一种通过Java实现的公众号Access_Token管理方法。利用Properties文件存储关键配置信息如AppID、AppSecret等,并读取和更新Access_Token及其有效期。通过这种方式实现了对公众号Access_Token的有效管理和维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做公众号,管理access_token一种方法,在src下新建properties文件;


package com;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;


public class PropertyTest {

	public void protest() throws IOException{
		
		String FileName = "WxToken.properties"; 
		// 从文件中获取token值及时间  
		Properties prop = new Properties();// 属性集合对象 
		//获取文件流  
		InputStream fis = PropertyTest.class.getClassLoader().getResourceAsStream(FileName);  
		prop.load(fis);// 将属性文件流装载到Properties对象中  
		fis.close();// 关闭流  
		//获取Appid,APPsecret  
		String AppID = prop.getProperty("AppID");  
		String AppSecret = prop.getProperty("AppSecret");  
		// 获取accesstoken,初始值为空,第一次调用之后会把值写入文件  
		String access_token = prop.getProperty("access_token");  
		String expires_in = prop.getProperty("expires_in");  
		String last_time = prop.getProperty("last_time"); 
		
		System.out.println(AppID);
		System.out.println(AppSecret);
		System.out.println(access_token);
		System.out.println(expires_in);
		System.out.println(last_time);
		
		prop.setProperty("access_token", access_token+"new");  
        prop.setProperty("last_time", System.currentTimeMillis() + "");  
        
        URL url_ = PropertyTest.class.getClassLoader().getResource(FileName);  
        FileOutputStream fos;
		try {
			fos = new FileOutputStream(new File(url_.toURI()));
			prop.store(fos, null);  
			fos.close();// 关闭流
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
		
	}
	
	public static void main(String[] args) throws IOException {
		PropertyTest p = new PropertyTest();
		p.protest();
	}
}
每次执行完后项目下的WxToken.properties内容不变,class目录下WxToken.properties已改变
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值