Home  >  Article  >  Java  >  Code example of java read and write operations

Code example of java read and write operations

不言
不言forward
2019-03-08 16:17:102787browse

This article brings you code examples about Java read and write operations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

java code:

Write:

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();
     }
}

Read:

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. When reading, the callback function should print console.log(JSON.parse(data.str)) ;

2. In order to ensure that there are no encoding format errors, it is recommended that the txt of the saved text should be set to the format of UTF-8.

The above is the detailed content of Code example of java read and write operations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete