Crawler4j學習筆記-util
util有兩個類,IO.java和Util.java。
IO.java用於文件的操作。
deleteFolder用於刪除文件夾(directory),實際通過deleteFolderContents刪除文件夾下的文件,遞歸調用deleteFolder刪除子文件夾,再刪除父文件夾。
這裏的用處是用來刪除持久化的url數據的。
當使用crawler4j時,需要配置保存url數據的文件夾(用於恢復上次操作),會在crawlStorageFolder新建文件夾frontier用於保存,而一般重新run Crawler4j時,需要刪除上次遺留下的數據,也就是frontier,這時就需要deleteFolder。
配置保存url數據的文件夾
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
frontier結構
同理writeBytesToFile就是用於將url保存起來的,不過其中用到了nio中的FileChannel和ByteBuffer。
FileChannel fc = new FileOutputStream(destination).getChannel();
fc.write(ByteBuffer.wrap(bytes));
fc.close();
FileChannel不能通過構造方法獲取實例,需要通過使用一個InputStream、OutputStream或RandomAccessFile獲取,通過ByteBuffer讀寫文件。
Util.java主要就是long、int和byte之間的轉換,以及用於判斷url指向的資源類型。
long、int和byte之間的轉換通過位運算和邏輯操作實現的,在這裏int是4 byte大小的,轉換時需要new byte[4]保存,同理long需要new byte[8]。
實現如下
public static byte[] int2ByteArray(int value) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (3 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
}
需要注意的是,假設value爲0x0A0B0C0D,那麼對應的關係(右爲最低字節),
no | [3] | [2] | [1] | [0] |
---|---|---|---|---|
value | 0A | 0B | 0C | 0D |
byte | b[3] | b[2] | b[1] | b[0] |
0D | 0C | 0B | 0A |
這樣的話,高位字節就保存到下標小的b中了,long2ByteArray也是一樣的。
需要注意,在putIntInByteArray方法中,沒有校驗offset>buf.length的。
public static void putIntInByteArray(int value, byte[] buf, int offset) {
for (int i = 0; i < 4; i++) {
int valueOffset = (3 - i) * 8;
buf[offset + i] = (byte) ((value >>> valueOffset) & 0xFF);
}
}
而判斷url指向的資源類型主要就是以response(String類型)裏面的content-type爲參數傳入判斷的,hasBinaryContent會判斷image、audio、video、application爲二進制的數據,而hasPlainTextContent則以text/plain爲據。
如
public static boolean hasBinaryContent(String contentType) {
if (contentType != null) {
String typeStr = contentType.toLowerCase();
if (typeStr.contains("image") || typeStr.contains("audio") || typeStr.contains("video") || typeStr.contains("application")) {
return true;
}
}
return false;
}