HuTool 工具類詳細介紹2 檔案操作工具類

2021-10-20 08:25:22 字數 3061 閱讀 8416

// 檔案的拷貝

bufferedinputstream in = fileutil.getinputstream("d:/桌面/hutool學習.md");

bufferedoutputstream out = fileutil.getoutputstream("d:/桌面/hutool學習複製.md");

long copysize = ioutil.copy(in, out, ioutil.default_buffer_size);

// 拷貝檔案的大小

system.out.println(copysize);

system.out.println("拷貝成功");

in.close();

out.close();

用於檔案型別的判斷,返回值為檔案的型別

file file = fileutil.file("d:/桌面/hutool學習.md");

string type = filetypeutil.gettype(file);

//輸出的是檔案的格式

console.log(type);

在以前,我們需要監聽檔案的變化:建立修改刪除等,需要進行遍歷來定時檢查檔案,效率很低,效能很差,所以有了這個工具類。

監聽指定事件

file file2 = fileutil.file("example.properties");

//這裡只監聽檔案或目錄的修改事件

watchmonitor watchmonitor = watchmonitor.create(file2, watchmonitor.entry_modify);

watchmonitor.setwatcher(new watcher()-> {}", currentpath, obj);

}@override

public void onmodify(watchevent<?> event, path currentpath) -> {}", currentpath, obj);

}@override

public void ondelete(watchevent<?> event, path currentpath) -> {}", currentpath, obj);

}@override

public void onoverflow(watchevent<?> event, path currentpath) -> {}", currentpath, obj);

}});

//設定監聽目錄的最大深入,目錄層級大於制定層級的變更將不被監聽,預設只監聽當前層級目錄

watchmonitor.setmaxdepth(3);

//啟動監聽

watchmonitor.start();

監聽全部事件

watchmonitor.createall(file, new ******watcher()

}).start();

//預設utf-8編碼,可以在構造中傳入第二個引數做為編碼

filereader filereader = new filereader("d:/桌面/hutool測試.txt");

string result = filereader.readstring();

system.out.println(result);

filewriter writer = new filewriter("d:/桌面/hutool測	試.txt");

writer.write("新增文字",true);

主要用於類似日誌這種(此類只有在寫入檔案的時候開啟檔案,寫入結束之後,此類不需要關閉

file file = new file("d:/桌面/hutool測試.txt");
有時候需要啟動執行緒來「監控檔案的變化,類似於linux下的tail -f命令

tailer tailer = new tailer(fileutil.file("d:/桌面/test.log"), tailer.console_handler, 2);

tailer.start();

實時列印檔案變化的類

/**

* 命令列列印的行處理器

* * @author looly

* @since 4.5.2

*/public static class consolelinehandler implements linehandler

}

該方法會阻塞執行緒

獲取檔名

file file = fileutil.file("d:/桌面/hutool學習.md");

// hutool學習.md

string name = filenameutil.getname(file);

system.out.println(name);

單獨獲取主檔名副檔名

file file1 = fileutil.file("d:/桌面/hutool學習.md");

// "hutool學習"

string name1 = filenameutil.mainname(file1);

system.out.println(name1);

// "md"

string name2 = filenameutil.extname(file1);

system.out.println(name2);

Hutool工具類使用

1 轉換為字串 int a 1 astr為 1 string astr convert.tostr a long b bstr為 1,2,3,4,5 string bstr convert.tostr b 2 轉換為指定型別陣列 string b 結果為integer陣列 integer intar...

CString類詳細介紹

這是本人第一次寫csdn部落格,如果有寫得不好的地方請各位大佬幫忙指出不足之處,本人定會謙虛請教。眾所周知,mfc 微軟基礎類庫 是基於windows介面開發的,它封裝了大部分的windows api 應用程式介面 函式,由c格式的函式公升級為類庫。而cstring字串類是mfc中比較常用的乙個類,...

CountDownLatch工具類介紹

countdownlatch是乙個同步工具類,它允許乙個或多個執行緒處於等待狀態直到在其它執行緒中執行的一組操作完成為止。countdownlatch用乙個給定的計數來實現初始化。await方法會一直處於阻塞狀態,直到countdown方法呼叫而使當前計數達到零。當計數為零之後,所有處於等待的執行緒...