java监听文件改名字_java 监听文件修改

在网上找了很多有关java监听文件修改的资料,很多都做得太复杂了;而且用到本地都有问题。这里自己写一个简单的监听文件修改的方法,代码如下: [java] view plaincopyprint? 01.package com.yunho.rule; 02. 03.import java.text.SimpleDateFormat; 04.impo

在网上找了很多有关java监听文件修改的资料,很多都做得太复杂了;而且用到本地都有问题。这里自己写一个简单的监听文件修改的方法,代码如下:    [java] view plaincopyprint?

01.package com.yunho.rule;

02.

03.import java.text.SimpleDateFormat;

04.import java.util.*;

05.import java.io.File;

06.import java.io.IOException;

07.

08.public class FileListener{

09.    /**

10.     * A facility for threads to schedule tasks for future execution in a background thread.

11.     * Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

12.     * */

13.    private Timer timer;

14.

15.    /**

16.     * current time

17.     * */

18.    private long currentTime=-1;

19.

20.    /**

21.     * last Modified Time

22.     * */

23.    private long lastModifiedTime=-1;

24.

25.    /**

26.     * 分钟

27.     * */

28.    private long times=1;

29.

30.    /**

31.     * time

32.     * */

33.    private long pollingInterval=1000 * times;

34.

35.    /**

36.     * file path

37.     * */

38.    private String filePath="src/com/yunho/rule/rule.xml";

39.

40.    public FileListener() {

41.        File file=new File(filePath);

42.        lastModifiedTime=file.lastModified();

43.        currentTime=lastModifiedTime;

44.    }

45.

46.    public static void main(String[] args) {

47.        FileListener fileListener=new FileListener();

48.        fileListener.timer = new Timer(true);

49.        fileListener.start();

50.    }

51.

52.    public void start(){

53.        timer.schedule(new FileMonitor(), 0, pollingInterval);

54.         while (true) {

55.            try {

56.                int ch = System.in.read();

57.                System.out.println("ch = "+ch);

58.                if (ch - 'c' == 0) {

59.                    System.out.println("QUIT");

60.                    timer.cancel();

61.                    break;

62.                }

63.            } catch (IOException e) {

64.                e.printStackTrace();

65.            }

66.        }

67.    }

68.

69.    private class FileMonitor extends TimerTask {

70.        public void run() {

71.            File file = new File(filePath);

72.            lastModifiedTime = file.exists() ? file.lastModified() : -1;

73.            if (currentTime != lastModifiedTime) {

74.                System.out.println(" File [ " + file.getName() + " ] changed At: "

75.                        + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS")。format(lastModifiedTime));

76.                currentTime = lastModifiedTime;

77.            }

78.        }

79.    }

80.}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值