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'}");
}
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章