Java ist auch eine Insel

Freitag, März 02, 2007

Find all hyperlinks in a text file

FileChannel     fc = new FileInputStream( "c:/a.html" ).getChannel();
ByteBuffer byteBuf = fc.map( FileChannel.MapMode.READ_ONLY, 0, fc.size() );
CharBuffer charBuf = Charset.defaultCharset().newDecoder().decode( byteBuf );
Pattern pattern = Pattern.compile( "<a.*?href=[\"']([^\"]*?)[\"'].*?>", Pattern.CASE_INSENSITIVE );
Matcher m = pattern.matcher( charBuf );

while ( m.find() )
System.out.println( m.group( 1 ) );

fc.close();

AddThis Social Bookmark Button

2 Comments:

  • interessante variante. - aber gibt es ausser dem offensichtlichen vorteil (?), dass der code sehr kompakt ist, noch andere vorteile gegenüber der old-school variante?

    Reader reader = new BufferedReader(
    new FileReader(this.filename));
    StringBuffer sb = new StringBuffer(1024);

    char[] chars = new char[1024];
    int numRead = 0;
    while( (numRead = reader.read(chars)) > -1)
    {
    sb.append(String.valueOf(chars, 0, numRead));
    }
    reader.close();

    Pattern pattern = Pattern.compile( "<a.*?href=[\"']([^\"]*?)[\"'].*?>", Pattern.CASE_INSENSITIVE );
    Matcher m = pattern.matcher( sb.toString() );

    while ( m.find() )
    {
    System.out.println( m.group( 1 ) );
    }

    p.s.: sorry für die üble formatierung

    By Anonymous lukas, at März 06, 2007 10:46 PM  

  • NIO ist in Java sehr schnell. Das ist ein großer Vorteil.

    By Blogger Christian Ullenboom, at März 06, 2007 10:49 PM  

Kommentar veröffentlichen

<< Home