文件6. 查找替换.txt文本文件中的内容

servlet实现对文本文件的查找替换

.jsp界面

 <form>
<table>
<tr>
<td>选择文本文件:</td>
<td><input type="text" name="filesPath" /></td>
</tr>
<tr>
<td>搜索文本:</td>
<td><input type="text" name="content" /></td>
</tr>
<tr>
<td>替换文本:</td>
<td><input type="text" name="replace" /></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="提交"/>
</td>
</tr>
</table>
</form>

.js代码

 $().ready(function(){
$("input[type='button']").click(function(){
var filesPath=$("input[name='filesPath'").val();
var con=$("input[name='content']").val();
var replace=$("input[name='replace']").val();
var xmlhttp=getXmlhttp();
var data={"filesPath":filesPath,"content":con,"replace":replace};
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
alert("转换完成!");
}
};
xmlhttp.open("POST","showFile","true");
xmlhttp.setRequestHeader("Content-Type","application/json");
xmlhttp.send(JSON.stringify(data));
});
});
//获取xmlHttp
function getXmlhttp() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest;
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}

servlet层ShowSomeType.java

 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
JSONObject data=getJsonObject(req);
String filesPath=data.getString("filesPath");
String content=data.getString("content");
String replace=data.getString("replace");
boolean seccess=false;
if(filesPath!=null && content!=null && replace!=null)
seccess=replaceFileStr(filesPath,content,replace);
System.out.println(seccess);
} private boolean replaceFileStr(String path, String str, String con) {
try {
FileReader fr=new FileReader(path);          //创建文件输入流
BufferedReader br=new BufferedReader(fr);      
char[] data=new char[1024];               //创建缓冲字符数组
int rn=0;
StringBuilder sb=new StringBuilder();         //创建字符串构件器
while((rn=fr.read(data))>0) {              //读取文件内容到字符串构件器
String content=String.valueOf(data,0,rn);     
sb.append(content);
}
fr.close();
String contentStr=sb.toString().replace(str,con);  //从构件器中生成字符串,并替换搜索文本
FileWriter font=new FileWriter(path);         //创建文件输出流
font.write(contentStr.toCharArray());         //把替换完成的字符串写入文件内
font.close();                       //关闭输出流
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} private JSONObject getJsonObject(HttpServletRequest req) {
StringBuffer json=new StringBuffer();
String lineString=null;
BufferedReader reader;
JSONObject data=null;
try {
reader = req.getReader();
while((lineString=reader.readLine())!=null) {
json.append(lineString);
}
data=JSONObject.fromObject(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
return data;
}

上一篇:java 集合遍历输出方式


下一篇:【原理探究】女朋友问我ArrayList遍历时删除元素的正确姿势是什么?