第一步:
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