java读写操作的代码示例

互联网 19-3-8
本篇文章给大家带来的内容是关于java读写操作的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

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读写操作的代码示例的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: java
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:springboot2.0整合同时支持jsp+html跳转的方法介绍(附代码)

相关资讯