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读写操纵的代码示例的细致内容,更多请关注ki4网别的相干文章!