專案需求
由於所在資料中台專案群組需要實現監聽資料夾或日誌檔案並讀取對應格式的髒資料的需求,以便在檔案、資料夾變更時進行對應的業務流程;所以在這裡記錄下相關業務的實現及技術選型。
Apache Commons-IO
首先需要加入對應依賴:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.7</version> </dependency>
版本可自行選擇,這裡要注意的是2.7 版本以上需要Java 8
官網截圖:
Apache Commos IO中的org.apache.commons.io.monitor
套件提供了文件系統監聽的功能。
核心知識
一句話總結:透過觀察者模式以及事件監聽機制,以
FileAlterationObserver
#為核心,再透過FileAlterationListener
,FileAlterationMonitor
,就可以實現對檔案系統的事件監聽。整體流程:
#自訂檔案監聽類別並繼承
FileAlterationListenerAdaptor
實作對文件與目錄的創建,修改,刪除事件的處理自訂檔案監控類,透過指定目錄創建一個觀察者
FileAlterationObserver
向此監視器新增檔案系統觀察器,並新增檔案監聽器
透過
ApplicationRunner
或CommandLineRunner
呼叫並執行
程式碼實作
檔案監聽類別:
/** * 文件监听类 * @author Greenarrow * @date 2022-05-12 14:43 **/ public class FileListener extends FileAlterationListenerAdaptor { private static Logger logger = LoggerFactory.getLogger(FileListener.class); @Override public void onStart(FileAlterationObserver observer) { super.onStart(observer); logger.info("onStart"); } @Override public void onDirectoryCreate(File directory) { logger.info("[新建]:" + directory.getAbsolutePath()); } @Override public void onDirectoryChange(File directory) { logger.info("[修改]:" + directory.getAbsolutePath()); } @Override public void onDirectoryDelete(File directory) { logger.info("[删除]:" + directory.getAbsolutePath()); } @Override public void onFileCreate(File file) { String compressedPath = file.getAbsolutePath(); logger.info("[新建]:" + compressedPath); List<String> contentList = null; try { if (file.canRead()){ // 将文件按行读取为字符串集合 contentList = FileUtils.readLines(new File(compressedPath), StandardCharsets.UTF_8); if (CollectionUtil.isNotEmpty(contentList)){ // 获取对应格式的数据并输出,这里可自行添加业务处理 List<String> dirtyRecord = contentList.stream().filter(s -> s.startsWith("{") && s.endsWith("}")).collect(Collectors.toList()); dirtyRecord.forEach(System.out::println); } } } catch (IOException e) { e.printStackTrace(); logger.error("读取文件内容失败",e); } } @Override public void onFileChange(File file) { String compressedPath = file.getAbsolutePath(); logger.info("[修改]:" + compressedPath); } @Override public void onFileDelete(File file) { logger.info("[删除]:" + file.getAbsolutePath()); } @Override public void onStop(FileAlterationObserver observer) { super.onStop(observer); logger.info("onStop"); } }
檔案監控類別:
/** * 文件监听测试 demo * @author Greenarrow * @date 2022-05-12 14:45 **/ public class FileMonitor { FileAlterationMonitor monitor = null; public FileMonitor(long interval) throws Exception { monitor = new FileAlterationMonitor(interval); } /** * 给文件添加监听 * @param path * @param listener */ public void monitor(String path, FileAlterationListener listener) { FileAlterationObserver observer = new FileAlterationObserver(new File(path)); monitor.addObserver(observer); observer.addListener(listener); } public void stop() throws Exception { monitor.stop(); } public void start() throws Exception { monitor.start(); } }#########自訂Runner 並實作###CommandLineRunner### :#########
/** * 项目启动之后开启文件监听功能 * @author Greenarrow * @date 2022-05-12 10:02 **/ @Component // @Order(Integer.MIN_VALUE) public class DirtyRecordRunner implements CommandLineRunner { private static Logger logger = LoggerFactory.getLogger(DirtyRecordRunner.class); @Value("${test}") private String path; @Override public void run(String... args) throws Exception { logger.info(this.getClass().getName()+"[开启文件夹监听功能]"); FileMonitor fileMonitor = new FileMonitor(1000); fileMonitor.monitor(path,new FileListener()); fileMonitor.start(); } }
以上是Java如何實作日誌檔案監聽並讀取相關數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavadevelovermentIrelyPlatForm-DeTueTososeVeralFactors.1)JVMVariationsAffectPerformanceNandBehaviorAcroSsdifferentos.2)Nativelibrariesviajnijniiniininiinniinindrododerplatefform.3)

Java代碼在不同平台上運行時會有性能差異。 1)JVM的實現和優化策略不同,如OracleJDK和OpenJDK。 2)操作系統的特性,如內存管理和線程調度,也會影響性能。 3)可以通過選擇合適的JVM、調整JVM參數和代碼優化來提升性能。

Java'splatFormentenceHaslimitations不包括PerformanceOverhead,versionCompatibilityIsissues,挑戰WithnativelibraryIntegration,Platform-SpecificFeatures,andjvminstallation/jvminstallation/jvmintenance/jeartenance.therefactorscomplicatorscomplicatethe“ writeOnce”

PlatformIndependendecealLowsProgramStormonanyPlograwsStormanyPlatFormWithOutModification,而LileCross-PlatFormDevelopmentRequiredquiresMomePlatform-specificAdjustments.platFormIndependence,EneblesuniveByjava,EnablesuniversUniversAleversalexecutionbutmayCotutionButMayComproMisePerformance.cross.cross.cross-platformd

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

javaispopularforcross-platformdesktopapplicationsduetoits“ writeonce,runany where”哲學。 1)itusesbytiesebyTecodeThatrunsonAnyJvm-備用Platform.2)librarieslikeslikeslikeswingingandjavafxhelpcreatenative-lookingenative-lookinguisis.3)

在Java中編寫平台特定代碼的原因包括訪問特定操作系統功能、與特定硬件交互和優化性能。 1)使用JNA或JNI訪問Windows註冊表;2)通過JNI與Linux特定硬件驅動程序交互;3)通過JNI使用Metal優化macOS上的遊戲性能。儘管如此,編寫平台特定代碼會影響代碼的可移植性、增加複雜性、可能帶來性能開銷和安全風險。

Java將通過雲原生應用、多平台部署和跨語言互操作進一步提昇平台獨立性。 1)雲原生應用將使用GraalVM和Quarkus提升啟動速度。 2)Java將擴展到嵌入式設備、移動設備和量子計算機。 3)通過GraalVM,Java將與Python、JavaScript等語言無縫集成,增強跨語言互操作性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver Mac版
視覺化網頁開發工具