服务器中访问Properties类型文件的例子

第一步:

 

1.在服务器中访问Properties文件,就不能跟普通的java project中访问Properties文件一样,java project中访问可以通过我们熟悉的方式(例如相对路径)获取到IO流,但在服务器中就不能这样获取,不同的服务器相对的路径不同

 

2.在服务器中访问文件使用Class对象提供的方法,按照classpath路径去读取文件(web标准)

 

3.输入流使用Class对象的getResourceAsStream()方法获得,例如:文件名为loginnum.properties,那么你的访问就应该为getClass().getResourceAsStream("/loginnum.properties");其中文件路径的"/"一定要写

 

4.输出流使用Class对象的getResource()方法获得,例如:文件名为loginnum.properties,那么你的访问就应该为getClass().getResource("/loginnum.properties").getFile();其中文件路径的"/"一定要写

 

5.下面是我的例子的目录结构,如下图所示:

 

6.下面是我写的工具类代码,使用单例去读取文件:

package util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;

public class PropertiesUtil {
	
	private static PropertiesUtil pu = new PropertiesUtil("/loginnum.properties");
	
	private PropertiesUtil(String filePath){
		this.filePath = filePath;
		this.properties = new Properties();
	}
	
	private String filePath;
	
	private Properties properties;
	
	private InputStream is;
	
	private OutputStream os;
	
	public String readValue(String key) {
		is = getClass().getResourceAsStream(filePath);
		try {
			properties.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String value = null;
		try {
			value = properties.getProperty(key);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
	
	public void writeValue(String key,String value){
		try {
			os = new FileOutputStream(getClass().getResource(filePath).getFile());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		properties.setProperty(key, value);
		try {
			properties.store(os,"Update:"+new Date());
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static PropertiesUtil getInstance(){
		return pu;
	}
}

 

参考资料:

1.http://zhuxinyu.iteye.com/blog/222910

2.http://blog.csdn.net/liangrockman/article/details/5777031

3.http://java.chinaitlab.com/advance/841846.html

4.http://www.cnblogs.com/diyunpeng/archive/2011/06/06/2073567.html 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值