JavaWeb项目读取和修改配置文件问题
来源:互联网 发布:单词社交网络 网盘 编辑:程序博客网 时间:2024/04/30 18:17
JavaWeb项目区别于普通Java项目,它会在服务器中编译,编译后的文件会存在服务器下的Webapps文件夹中,因此,在项目发布后,修改.properties文件,路径成了问题。
InputStream input =PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
像上面的加载方式,修改.properties文件后,会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件信息,而不是再次读取。因此要转变输入流获取方式。
String path=PropertiesUtil.class.getClassLoader().getResource(file).getPath();InputStream input=new FileInputStream(path);
下面是我封装的工具类,请多指教。
package com.yc.utils;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.Properties;/** * 加载 .properties 文件工具类 * @author S3 * */public class PropertiesUtil {public static Map<String, String> readProperties(String file) throws IOException{Map<String, String> map=new HashMap<String,String>();String path=PropertiesUtil.class.getClassLoader().getResource(file).getPath();InputStream input=new FileInputStream(path);BufferedReader bf=new BufferedReader(new InputStreamReader(input));Properties p = new Properties();try {p.load(bf);} catch (IOException e) {e.printStackTrace();}finally{input.close();bf.close();}if(p.getProperty("name")!=null && p.getProperty("tel")!=null){map.put("name", p.getProperty("name"));map.put("tel", p.getProperty("tel"));return map;}return null;} //修改方法public static void writeProperties(String file,String name,String tel) throws IOException{FileOutputStream fos = null;try {fos=new FileOutputStream(PropertiesUtil.class.getClassLoader().getResource(file).getPath());Properties p =new Properties();p.setProperty("name", name);p.setProperty("tel", tel);p.store(fos,"保存");} catch (FileNotFoundException e) {e.printStackTrace();}finally{fos.close();}} //测试类public static void main(String[] args) throws IOException {System.out.println(readProperties("admin.properties"));writeProperties("admin.properties", "a", "110");}}
0 0
- JavaWeb项目读取和修改配置文件问题
- javaWeb项目中读取配置文件
- javaWeb项目中读取配置文件
- javaWeb项目读取properties配置文件
- JavaWeb项目中读取配置文件的方式
- java web项目中读取和修改properties配置文件
- C# 读取配置文件和修改
- C# 读取配置文件和修改
- javaweb工程 配置文件读取
- 读取配置文件 + 修改配置文件
- java读取和修改ini配置文件
- java读取和修改ini配置文件
- Java读取和修改ini配置文件
- MFC ini 配置文件修改和读取键值
- Java读取和修改ini配置文件
- (转载)C# 读取配置文件和修改
- 用ConfigurationManager读取和修改配置文件
- java读取和修改ini配置文件
- 公共子串 字符串哈希
- 二级指针传参的解释和函数指针的理解
- 卷积神经网络(CNN)
- Linux入门笔记之文件权限(二)
- Java静态修饰符static
- JavaWeb项目读取和修改配置文件问题
- #cs231n#Assignment2:BatchNormalization.ipynb
- 校园地图
- 各个行业分类标准
- 【bzoj4034】[HAOI2015]T2
- 四.文件自校验大小破解(GetFileSize)
- PAT-A 1029. Median (25)
- GYM 101149 I.It's the Police(水~)
- codeforces 791B