一个properties文件的读取搞了一下午,终于搞好了,总结下经验:主要是path的设置:
1.readProperties(String key)方法读取的时候path的路径固定不变。
2.写入数据的时候,卧槽,最为致命,因为没有getResourceAsStream(propertiesName)方法,并且web程序一般在服务器的webapp文件夹中运行(比如tomcat),所以 必须用读写流直接读文件,但是我试过相对路径是不行的,会报错:找不到指定路径,绝对路径写死了也不行,所以用以下方法 String path = this.getClass().getResource("/").getPath() 此时的path为 /E:/Tomcat/apache-tomcat-7.0.72-windows-x64/apache-tomcat-7.0.72/webapps/syngis-web-map/WEB-INF/classes/ 然后再和poperties的名称拼接 成一个绝对路径,就好了。
3.注意String path = this.getClass().getResource("").getPath() 是 /E:/Tomcat/apache-tomcat-7.0.72-windows-x64/apache-tomcat-7.0.72/webapps/syngis-web-map/WEB- INF/classes/ 而String path = this.getClass().getResource("/").getPath()是/E:/Tomcat/apache-tomcat-7.0.72-windows-x64/apache-tomcat-7.0.72/webapps/syngis-web-map/WEB- INF/classes/com/wlw/service/impl/ 不难看出带“/”的路径到classes,不带的路径是自己文件所属路径。
private static final String propertiesName = "/filePath.properties";
/**
*
* @Title: readProperties
* @Description: TODO(读取配置文件)
* @param name 配置文件名称
* @return Iterator<String> 返回类型
* @throws
*/
public static String readProperties(String key) throws IOException{
Properties pro = new Properties();
//获取propreties文件的路径并且写入流
InputStream in = Tools.class.getResourceAsStream(propertiesName);
//载入流
pro.load(in);
//获取相应值
String value = pro.getProperty(key);
return value;
}
/**
* @throws IOException
* @Title: writeProperties
* @Description: TODO(将数据写入properties文件)
* @param 设定文件
* @return void 返回类型
* @throws
*/
public static void writeProperties(String key,String value,String path) throws IOException{
Properties pro = new Properties();
//获取properties的路径,最为重要
//String path = this.getClass().getResource("/").getPath();
//因为Tools为static所有不能用this.class方法
File file = new File(path+"filePath.properties");
FileOutputStream out = new FileOutputStream(file,false);//false不追加修改,删除修改
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
pro.setProperty(key, value);
System.out.println(key+":"+value);
pro.store(out,null);
out.close();
}