java 監聽檔案修改

來源:互聯網
上載者:User
原創作品,允許轉載,轉載時請務必以超連結形式標明文章 原始出處 、作者資訊和本聲明。否則將追究法律責任。http://blog.csdn.net/love254443233/article/details/7972525

在網上找了很多有關java監聽檔案修改的資料,很多都做得太複雜了;而且用到本地都有問題。這裡自己寫一個簡單的監聽檔案修改的方法,代碼如下:

package com.yunho.rule;import java.text.SimpleDateFormat;import java.util.*;import java.io.File;import java.io.IOException;public class FileListener{/** * A facility for threads to schedule tasks for future execution in a background thread.  * Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.  * */private Timer timer;/** * current time * */private long currentTime=-1;/** * last Modified Time * */private long lastModifiedTime=-1;/** * 分鐘 * */private long times=1;/** * time * */private long pollingInterval=1000 * times;/** * file path * */private String filePath="src/com/yunho/rule/rule.xml";public FileListener() {File file=new File(filePath);lastModifiedTime=file.lastModified();currentTime=lastModifiedTime;}public static void main(String[] args) {FileListener fileListener=new FileListener();fileListener.timer = new Timer(true);fileListener.start();}public void start(){timer.schedule(new FileMonitor(), 0, pollingInterval); while (true) {try {int ch = System.in.read();System.out.println("ch = "+ch);if (ch - 'c' == 0) {System.out.println("QUIT");timer.cancel();break;}} catch (IOException e) {e.printStackTrace();}}}private class FileMonitor extends TimerTask {public void run() {File file = new File(filePath);lastModifiedTime = file.exists() ? file.lastModified() : -1;if (currentTime != lastModifiedTime) {System.out.println(" File [ " + file.getName() + " ] changed At: "+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(lastModifiedTime));currentTime = lastModifiedTime;}}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.