首页 > 编程语言 > 详细

java 读写操作

时间:2019-03-08 13:32:36      阅读:128      评论:0      收藏:0      [点我收藏+]

java代码:

写入:

public void getNotice(HttpServletRequest request, String notice){
String message = JSON.toJSONString(notice);
File file = new File(request.getRealPath("/text/history.txt"));//这里是绝对路径。括号内的路径自己根据自己存放的路径来写。
try(OutputStreamWriter op = new OutputStreamWriter(new FileOutputStream(file , true), "utf-8")){
if(!file.exists()){
file.createNewFile();
}
op.append(message);
op.write("\r\n");//这里是换行,根据自己需求加与不加。
op.flush();
op.close();
}catch(IOException e){
e.printStackTrace();
} }

 

读取:

public void postNotice (HttpServletRequest request, HttpServletResponse response){
JSONObject json = new JSONObject();
String message ="";
File file = new File(request.getRealPath("/text/history.txt"));
try{
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] buff = new byte[1024];
while((len = in.read(buff))!= -1){
message = new String(buff,0 ,len, "utf-8);
}
}catch(IOException e){

}
String str1 = JSONObject.toJSONString(message.replaceAll("\r|\n", ""));//如果上述的换行未写,这句可以不用
json.put("str", str1);
returnMessage(response ,json); }

 

1.读取时,回调函数内应打印    console.log(JSON.parse(data.str));

2.为保证不出现编码格式错误 ,建议保存文本的txt 应设置为UTF-8的格式。

java 读写操作

原文:https://www.cnblogs.com/wuliMan/p/10495085.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!