需求:将文本放在服务器下,并修改文本中的值,
1,获取服务器地址
public Configuration getStandardConfig() {
//获取服务器的webapp路径
ServletContext context = ServletActionContext.getServletContext();
File file = new File(context.getRealPath("/"));
String path = file.getParentFile().getParentFile().getParentFile().getAbsolutePath();
Configuration standardConfig = new Configuration(path+"\\listSvr.ini");
return standardConfig;
}
2.将值写入文本中
public static void replaceTxtByStr(String oldStr,Integer replaceStr) {
String temp = "";
Properties prop = new Properties();
try {
//获取服务器的webapp路径
ServletContext context = ServletActionContext.getServletContext();
File file1 = new File(context.getRealPath("/"));
String path = file1.getParentFile().getParentFile().getParentFile().getAbsolutePath();
File file = new File(path+"\\listSvr.ini");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该行前面的内容
// 保存该行前面的内容
for (int j = 1; (temp = br.readLine()) != null
&& !(temp.replaceAll(" ", "").split("=")[0].toString()).equals(oldStr); j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
/**当所写行的=前面的内容与oldStr相同时,修改本行中的内容
*修改后的值为temp1
*/
String temp1 = temp.replaceAll(temp.replaceAll(" ", "").split("=")[1].toString(), "" +replaceStr);
buf = buf.append(temp1);
// 保存该行后面的内容
while ((temp = br.readLine()) != null) {
buf = buf.append(System.getProperty("line.separator"));
buf = buf.append(temp);
}
br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}