java缓存读写文件小例子



Java代码 收藏代码
  1. package com.taoniwu;  

  2. import java.util.regex.*;  

  3. import java.io.*;  

  4. publicclass TestRead {  

  5. publicstaticvoid main (String[] args) {  

  6.        File file=new File ("D://web.txt");  

  7. try

  8.        {  

  9.            BufferedReader input=new BufferedReader (new FileReader (file) );  

  10.            String text;  

  11. int sum = 0;  

  12.            File txt = new File("d://web.html");  

  13. //判断文件是否存在

  14. if(!txt.exists()){  

  15.                txt.createNewFile();  

  16.            }  

  17. else{  

  18.                txt.delete();  

  19.            }  

  20.            FileWriter fw=new FileWriter( "d://web.html",true);  

  21.            BufferedWriter bw=new BufferedWriter(fw);  

  22.            String sr = "";  

  23. while ( (text=input.readLine() ) !=null) {  

  24. //正则表达,过滤非www开头的网址

  25.                Pattern p = Pattern.compile ("http://www.*./");  

  26.                Matcher m = p.matcher (text);  

  27. while (m.find()) //查找符合pattern的字符串

  28.                {  

  29. //过滤带”baidu“和带”tarena”的url,并叠加链接代码

  30. if(m.group().indexOf("baidu") == -1 && m.group().indexOf("tarena") == -1 && m.group().indexOf("aowin") == -1)  

  31.                    {  

  32.                        sr = sr + sum + "、<a target="_blank" href=""+m.group()+"">"+m.group()+"</a><br />n";  

  33.                        sum++;  

  34.                    }  

  35. //添加缓存,当缓存达到30k时写入,并把sr清空

  36. if(sr.length()>30720){  

  37.                        bw.write(sr);  

  38.                        sr = "";  

  39.                    }  

  40.                }  

  41.            }  

  42.            bw.write(sr+"n");  

  43.            bw.close();  

  44.        } catch (Exception ex) {  

  45.            System.out.println (ex+"错误");  

  46.        }  

  47.        System.out.println("完成!");  

  48.    }  

  49. }  



代码来自: http://www.taoniwu.com/archives/2984.html


你可能感兴趣的:(java缓存)