本篇文章给大家带来的内容是关于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读写操作的代码示例的详细内容,更多请关注Work网其它相关文章!

09-02 11:14