web项目读写配置文件

因为配置文件在src下所以会编译到WEB-INF/classes下面,这是一个安全路劲没法通过URL直接访问

java对文件的操作需要绝对路劲,因为操作文件是使用OS的文件系统,没有绝对路劲就没办法找到文件

1.读配置文件

public class ProsUtil{
private static String PROS_CONFIG_FILE = "config/pros/web.properties";
private staitc String username;
private static String password;
static{
try {
InputStream is = ProsUtil.class.getClassLoader().getResourceAsStream(PROS_CONFIG_FILE);
Properties props = new Properties();
props.load(is);
username = props.getProperty("username");
password = props.getProperty("password-plugin");
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getUsername(){
return username;
}
public static String getPassword(){
return password;
}
}

2.写配置文件

方法一:

public class UserAction{
private PrintWriter out = ServletActionContext.getResponse().getWriter();
public void execute(){
String classPath = this.getClass().getResource("/").getFile();// 或.getPath()
String prosPath = "config/pros/admin.properties";
Properties pro = new Properties();
InputStream is = UserAction.class.getClassLoader().getResourceAsStream(prosPath);
try{
pro.load(is);
pro.setProperty("username", this.username);
pro.setProperty("password", this.password);
OutputStream os = new FileOutputStream(UserAction.class.getClassLoader().getResource(prosPath).getPath());
pro.store(os, null);
os.flush();
is.close();
os.close();
out.print("{success:true,'msg':'success'}");
}catch(Exception e){
e.printStackTrace();
out.print("{success:false,'msg':'fail'}");
}
}
}

方法二:

public class UserAction{
private PrintWriter out = ServletActionContext.getResponse().getWriter();
public void execute(){
String classPath = this.getClass().getResource("/").getFile();// 或.getPath()
String prosPath = "config/pros/admin.properties";
Properties pro = new Properties();
InputStream is = UserAction.class.getClassLoader().getResourceAsStream(prosPath);
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(classPath+prosPath)));
bw.write("username="+this.adminName);
bw.newLine();
bw.write("password="+this.adminPassword);
bw.close();
out.print("{success:true,'msg':'success'}");
}catch(Exception e){
e.printStackTrace();
out.print("{success:false,'msg':'fail'}");
}
}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值