一句代码完成对文本文件读取和写入

在jsp页面里,只需要两句代码就能够同时完成对文本文件的读取和写入.
java 代码
  1. import java.io.*;   
  2.   
  3. public class OP_File {   
  4.     public BufferedReader bufread;   
  5.     public BufferedWriter bufwriter;   
  6.     File writefile;   
  7.     String filepath, filecontent, read;   
  8.     String readStr = "";   
  9.   
  10.     public String readfile(String path) //从文本文件中读取内容     
  11.     {   
  12.         try {   
  13.             filepath = path; //得到文本文件的路径   
  14.             File file = new File(filepath);   
  15.             FileReader fileread = new FileReader(file);   
  16.             bufread = new BufferedReader(fileread);   
  17.             while ((read = bufread.readLine()) != null) {   
  18.                 readStr = readStr + read;   
  19.             }   
  20.         } catch (Exception d) {   
  21.             System.out.println(d.getMessage());   
  22.         }   
  23.         return readStr; //返回从文本文件中读取内容   
  24.     }   
  25.   
  26.     //向文本文件中写入内容   
  27.     public void writefile(String path, String content, boolean append) {   
  28.         try {   
  29.             boolean addStr = append; //通过这个对象来判断是否向文本文件中追加内容   
  30.             filepath = path; //得到文本文件的路径   
  31.             filecontent = content; //需要写入的内容   
  32.             writefile = new File(filepath);   
  33.             if (writefile.exists() == false//如果文本文件不存在则创建它    
  34.             {   
  35.                 writefile.createNewFile();   
  36.                 writefile = new File(filepath); //重新实例化   
  37.             }   
  38.             FileWriter filewriter = new FileWriter(writefile, addStr);   
  39.             bufwriter = new BufferedWriter(filewriter);   
  40.             filewriter.write(filecontent);   
  41.             filewriter.flush();   
  42.         } catch (Exception d) {   
  43.             System.out.println(d.getMessage());   
  44.         }   
  45.     }   
  46. }   

jsp文件

  1. <%@ page contentType="text/html;charset=GB2312" %>  
  2. <%@ page import="java.io.*" %>  
  3. <html>  
  4. <head>head>  
  5. <body>  
  6. <jsp:useBean id="filecontrol" class="count.OP_File" scope="page"/>  
  7. <%    
  8.  filecontrol.writefile("aa.txt","liuxiantong",false);   
  9.               //方法参数("路径","内容",true/false)--->是否追加   
  10.  String string=filecontrol.readfile("aa.txt");   
  11.               //方法:返回字符串 参数("路径")   
  12.  out.println(string);  //将读到的内容输出   
  13. %>  
  14. body>  
  15. html>  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值