java中properties配置文件的操作

package com.voip.server.configuration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class FileProcess
{
    /**
     * 日志工具
     */
    private static Logger logger = Logger.getLogger(FileProcess.class);

    /**
     * 文件处理实例
     */
    private static FileProcess instance = null;


    /**
     * default constructor 采用单例模式
     */
    private FileProcess()
    {

    }


    /**
     * 得到文件处理单例
     *
     * @return
     */
    public static synchronized FileProcess getInstance()
    {
        if (null == instance)
        {
            instance = new FileProcess();
        }
        return instance;
    }


    /**
     * 加载Properties配置文件至内存
     *
     * @param fileName
     * @return
     */
    public Properties loadProperties(String fileName)
    {
        if (null == fileName)
        {
            logger.error("file name is null.");
            return null;
        }
        Properties prop = new Properties();
        File file;
        FileInputStream in = null;
        try
        {
            file = new File(fileName);
            in = new FileInputStream(file);
            prop.load(in);
        }
        catch (IOException ex)
        {
            logger.error("load properties config file failed, cause:" + ex);
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException e)
            {
                logger.error(e);
            }
        }

        return prop;
    }


    /**
     * 保存Properties至配置文件
     *
     * @param prop
     * @param fileName
     * @return
     */
    public boolean saveProperties(Properties prop, String fileName)
    {
        // 参数校验
        if ((prop == null) || (fileName == null))
        {
            logger.error("The input parameter is invalid.");
            return false;
        }
        File file = null;
        FileOutputStream out = null;
        boolean result = false;
        try
        {
            file = new File(fileName);
            out = new FileOutputStream(file);
            prop.store(out, "");
            result = true;
        }
        catch (IOException ex)
        {
            logger.error("save properties file failed. cause:" + ex);
        }
        finally
        {
            try
            {
                out.close();
            }
            catch (IOException e)
            {
                logger.error("close file failed. cause:" + e);
            }
        }
        return result;
    }
}

转自软件技术共享网:http://itshare.17gigs.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值