朋友要一个邮件抓取器,边查边写了一个:
三个类
1.MyFrame,就是一些布局和事件。
?
package com.zhuzhu; import java.awt.Button; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MyFrame { public static void main(String args[]){ TextField tfin,tfout; Frame f = new Frame(); tfin = new TextField(10); tfin.setText("输入路径"); tfout = new TextField(10); tfout.setText("输出路径"); Button b1 = new Button("提取邮件地址"); Monitor monitor = new Monitor(tfin,tfout); b1.addActionListener(monitor); FlowLayout layout =new FlowLayout(); f.setLayout(layout); f.add(tfin); f.add(tfout); f.add(b1); f.setLocation(300, 300); f.setSize( 300,80); f.setBackground( Color.white); f.setResizable(true); f.setVisible( true); } }
?2.Monitor监听器类,对事件进行监听。
?
package com.zhuzhu; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; class Monitor implements ActionListener { TextField tfin,tfout; public Monitor(TextField tfin,TextField tfout){ this.tfin = tfin; this.tfout = tfout; } MyFrame tf = null; public Monitor(MyFrame tf) { this.tf = tf; } public void actionPerformed(ActionEvent e) { String indir = (String)tfin.getText(); String outdir = (String)tfout.getText(); System.out.println(indir); System.out.println(outdir); Spider sp = new Spider(); try { sp.readfile(indir,outdir); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
?3.Spider匹配地址的作用,system.out重定向的自定的流。
?
package com.zhuzhu; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Spider { public void readfile(String indir,String outdir) throws IOException { PrintStream out = new PrintStream(outdir); try { BufferedReader br = new BufferedReader(new FileReader(indir)); String line = ""; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } spider(sb.toString(), out); } catch (Exception e) { } } private static void spider(String line, PrintStream out) throws IOException { try { String regx = "[\\w[.-]]+@[\\w[.-]]+\\.[\\w]{3}"; Pattern p = Pattern.compile(regx); Matcher m = p.matcher(line); System.setOut(out); while (m.find()) { System.out.append(m.group()); System.out.println(); } out.close(); } catch (Exception e) { } } }
?运行了一下,貌似可以用。可能有很多bug,抛砖引玉了。
付上代码。下一步写如何自动转发。