现在的位置: 首页 > 综合 > 正文

Web项目Java读取Properties文件出现“The system cannot find the file specified”解决

2013年04月08日 ⁄ 综合 ⁄ 共 2035字 ⁄ 字号 评论关闭
文章目录

环境

 

MyEclipse 8.6 + JDK 1.6.31

 

问题

 

控制台测试读取配置文件正常,但部署到Tomcat后,再次读取,出现如下错误:

The system cannot find the file specified

 

解决

 

首先请读者参考控制台可以正常读取的代码:

 

package com.axt.sms.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * 
 * @version 1.0
 * @since JDK 1.6
 */
public class PropertiesConfig {  
	  
    /** 
     */  
    public static Properties readData(String filePath) {  
    	filePath = getRealPath(filePath);
        Properties props = new Properties();  
        try {  
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));  
            props.load(in);  
            in.close();  
            return props;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
    
    public static Properties readDBData(){
    	Properties props = new Properties();
    	try {
			props.load(new FileInputStream("db.properties").getClass().getResourceAsStream("db.properties"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return props;
    }
    private static String getRealPath(String filePath) {
    	return PropertiesConfig.class.getResource("/" + filePath).toString().substring(6);
    }
}  

 

再次看改进后的代码:

 

package com.axt.sms.util;

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

public class PropertiesUtil {
	private InputStream inputStream;
	private Properties properties;
	
	public PropertiesUtil(String fileName) {
		inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);    
		properties = new Properties();  
	}
		
	/**
	 * 获得签名
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String getSignature() throws UnsupportedEncodingException{
		try {    
			properties.load(inputStream);    
		} catch (IOException e1) {    
			e1.printStackTrace();    
		} 
		return new String(properties.getProperty("signature").getBytes("ISO-8859-1"), "UTF-8");
	}
		
	public static void main(String[] args) {
		try {
			System.out.println(new PropertiesUtil("sms.properties").getSignature());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}

 

总结

 

部署到Tomcat服务器后,应该采取绝对路径。因部署到服务器后,目录路径是动态变化的,应该使用getResourceAsStream方法。

 

 

 

katoon Sina  

CSDN
@Wentasy 博文仅供参考,欢迎大家来访。如有错误之处,希望批评指正。原创博文如需转载请注明出处,谢谢 :) [CSDN博客]

抱歉!评论已关闭.