当前位置: 代码迷 >> Web前端 >> 从web工程的src索引下读取.properties文件
  详细解决方案

从web工程的src索引下读取.properties文件

热度:98   发布时间:2013-03-26 09:54:34.0
从web工程的src目录下读取.properties文件
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class FtpURLUtil
{
    /**
     * 日志组件
     */
    private static Logger logger = Logger.getLogger(FtpURLUtil.class.getName());

    private static FtpURLUtil instance = null;
    
    /**
     * 用于存放上传文件的目录
     */
    private String uploadPath;

    /**
     * 配置文件名称
     */
    private String configFileString = "ftpURL.properties";

    /**
     * 读取文件后的结果
     */
    private String exeResult;

    /**
     * 只允许创建一个实例对象
     */
    private FtpURLUtil()
    {
    }

    /**
     * 创建本类的单例
     * <p/>
     * getInstance(单例)
     *
     * @return FtpURLUtil对象
     */
    public static FtpURLUtil getInstance()
    {
        if (instance == null)
        {
            instance = new FtpURLUtil();
        }
        return instance;
    }

    /**
     * 读取配置文件
     *
     * @return boolean
     */
    public boolean readConfigFile()
    {
        //读取配置文件     
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(configFileString);

        //读路径出错,换另一种方式读取配置文件
        if (null == inputStream)
        {
            logger.error("read config file failed.");
            this.exeResult = "upload_read_config_file_failed";
            return false;
        }

        //读取配置文件中的appid和moduleId
        Properties p = new Properties();

        try
        {
            p.load(inputStream);
        }
        catch (IOException e1)
        {
            logger.error("Load config file failed." + e1);
            this.exeResult = "upload_load_config_file_failed";
            return false;
        }
        //得到文件路径
        this.uploadPath = p.getProperty("path");
        //判断文件路径是否存在
        try
        {
            File filePath = new File(this.uploadPath.trim());

            if (!filePath.exists())
            {
                this.exeResult = "upload_file_path_no_exist";
                return false;
            }
        }
        catch (Exception e)
        {
            logger.error("read filepath failed." + e);
            this.exeResult = "upload_file_path_no_exist";
            return false;
        }

        return true;
    }

    public String getExeResult()
    {
        return exeResult;
    }

    public void setExeResult(String exeResult)
    {
        this.exeResult = exeResult;
    }

    public String getUploadPath()
    {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath)
    {
        this.uploadPath = uploadPath;
    }
}
  相关解决方案