java缓存读写文件小例子

在一个叫掏你屋的博客上看到的小例子,缓存读写文件:

 

  1. package com.taoniwu; 
  2. import java.util.regex.*; 
  3. import java.io.*; 
  4.  
  5. public class TestRead { 
  6.     public static void main (String[] args) { 
  7.         File file=new File ("D://web.txt"); 
  8.  
  9.         try 
  10.         { 
  11.             BufferedReader input=new BufferedReader (new FileReader (file) ); 
  12.             String text; 
  13.             int sum = 0
  14.             File txt = new File("d://web.html"); 
  15.             //判断文件是否存在 
  16.             if(!txt.exists()){ 
  17.                 txt.createNewFile(); 
  18.             } 
  19.             else
  20.                 txt.delete(); 
  21.             } 
  22.             FileWriter fw=new FileWriter( "d://web.html",true); 
  23.             BufferedWriter bw=new BufferedWriter(fw); 
  24.             String sr = ""
  25.             while ( (text=input.readLine() ) !=null) { 
  26.                 //正则表达,过滤非www开头的网址 
  27.                 Pattern p = Pattern.compile ("http://www.*./"); 
  28.                 Matcher m = p.matcher (text); 
  29.                 while (m.find()) //查找符合pattern的字符串 
  30.                 { 
  31.                     //过滤带”baidu“和带”tarena”的url,并叠加链接代码 
  32.                     if(m.group().indexOf("baidu") == -1 && m.group().indexOf("tarena") == -1 && m.group().indexOf("aowin") == -1
  33.                     { 
  34.                         sr = sr + sum + "、" href=""+m.group()+"">"+m.group()+"
    n"
  35.                         sum++; 
  36.                     } 
  37.                     //添加缓存,当缓存达到30k时写入,并把sr清空 
  38.                     if(sr.length()>30720){ 
  39.                         bw.write(sr); 
  40.                         sr = ""
  41.                     } 
  42.                 } 
  43.             } 
  44.             bw.write(sr+"n"); 
  45.             bw.close(); 
  46.  
  47.         } catch (Exception ex) { 
  48.             System.out.println (ex+"错误"); 
  49.         } 
  50.         System.out.println("完成!"); 
  51.     } 

 

你可能感兴趣的:(Java,java,file,string,exception,import,input)