Home > Java > javaTutorial > body text

Code example of java read and write operations

不言
Release: 2019-03-08 16:17:10
forward
2799 people have browsed it

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

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);
}
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template