java 监听文件修改

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

在网上找了很多有关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.}

而是深沉的意志恢弘的想象炙热的恋情;青春是生命的深泉在涌流。

java 监听文件修改

相关文章:

你感兴趣的文章:

标签云: