java正则NIO截取有用信息实例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by niuzy on 2018-03-13.
 */
public class PatternTest {

    private static Pattern pattern = Pattern.compile("<h(2|3)>(\\d+.*)</h(2|3)>");
    private static Pattern pattern1 = Pattern.compile("<div>((http|localhost|192.168|\\{\\{base).*)</div>");

    public static void main(String[] args) throws IOException {
        File file = new File("F:/业务代码文档/接口文件/运营管理系统.html");
        FileChannel fileChannel = new FileInputStream(file).getChannel();
        FileChannel fileChannel1 = new FileOutputStream("F:/业务代码文档/接口文件/运营管理系统干货.html").getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY,0,fileChannel.size());
        Charset charset = Charset.forName("UTF-8");
        CharBuffer charBuffer = charset.decode(mappedByteBuffer);
        long l = charBuffer.length();
        int begin = 0;
        int end = 0;
        for(int i=0;i<l;i++){
            end = i;
            if(charBuffer.get(i)==13||charBuffer.get(i)==10){
                String str = charBuffer.subSequence(begin,end).toString();
                if(match(str)) {
                    byteBuffer.clear();
                    byte[] bytes = str.getBytes("utf-8");
                    int pos = 0;
                    while (bytes.length > pos) {
                        byteBuffer.put(bytes, pos, bytes.length - pos > byteBuffer.capacity() ? byteBuffer.capacity() : bytes.length - pos);
                        byteBuffer.flip();
                        fileChannel1.write(byteBuffer);
                        pos = pos + byteBuffer.capacity();
                    }
                }
                begin = end;
            }
        }
        fileChannel.close();
        fileChannel1.close();
    }


    public static boolean match(String str){
        Matcher matcher = pattern.matcher(str);
        if(matcher.find()){
            return true;
        }
        matcher = pattern1.matcher(str);
        if(matcher.find()){
            return true;
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值