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;
}
}
java正则NIO截取有用信息实例
最新推荐文章于 2022-08-25 15:03:46 发布