java对文件的读写

本文介绍了一个简单的Java代码实现文件的读写操作,包括如何从配置文件加载属性以及如何向配置文件写入数据。适用于项目开发中配置管理的需求。

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

最近在做公司的项目,看到代码中有个对文件的读写的,贴出来,一是为了记录下,以后用到时方便了,二来呢,给大家分享下,很简单的一点代码

package com.suning.ebuy.zone.review.utils;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import com.suning.framework.lang2.SnfLogger;
import com.suning.framework.lang2.SnfLoggerFactory;
import com.suning.framework.lang2.dto.EventMessage;


public class GetProperties {
	private static final SnfLogger logger          = SnfLoggerFactory.getLogger(GetProperties.class);
	private static Properties properties = new Properties();

	public static Properties getProperties() {
		return properties;
	}

	public static void setProperties(Properties properties) {
		GetProperties.properties = properties;
	}
	//利用静态代码块初始化数据
	static{
		InputStream in = GetProperties.class.getResourceAsStream("/conf/orderShow.properties");
		if(in==null){
			logger.info("importLog.properties not found");
		}else{
			if(!(in instanceof BufferedInputStream)){
				in = new BufferedInputStream(in);
			}
			try{
				properties.load(in);
				in.close();
			}catch (Exception e) {
				logger.info("Error while processing importLog.properties");
			}
		}
	}
	/**
	 * 向properties文件中写入数据
	 */
	public static  void writeProperties(String parameterName,
			String parameterValue) {
		logger.info("enter:GetProperties类中的方法:writeProperties:");
		OutputStream fos = null;
		try {
			fos = new FileOutputStream("/conf/orderShow.properties");   
			properties.setProperty(parameterName, parameterValue);   
            // 将此 Properties 表中的属性列表(键和元素对)写入输出流   
			properties.store(fos, "『comments』Update key:" + parameterName);   
		} catch (IOException e) {
			EventMessage eventMessage = new EventMessage();
            eventMessage.setFunctionName(ExceptionUtil.getCurrentMethodName());
            logger.logException(eventMessage, e);
			
		}finally{
			if(null != fos){
				try {
					fos.close();
				} catch (IOException e) {
					logger.warn("IO ERROR:" + e.getMessage());
				}
			}
		}
		logger.info("exit:GetProperties类中的方法:writeProperties:");
	}
	
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值