监控文件 java_java实现文件监控

public

class

MainFrame

extends

JFrame {

private

JPanel contentPane;

private

JTextField textField;

private

JTextArea textArea;

public

static

void

main(String[] args) {

EventQueue.invokeLater(

new

Runnable() {

public

void

run() {

try

{

MainFrame frame

=

new

MainFrame();

frame.setVisible(

true

);

}

catch

(Exception e) {

e.printStackTrace();

}

}

});

}

public

MainFrame() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(

100

,

100

,

543

,

300

);

contentPane

=

new

JPanel();

contentPane.setBorder(

new

EmptyBorder(

5

,

5

,

5

,

5

));

setContentPane(contentPane);

contentPane.setLayout(

null

);

JLabel label

=

new

JLabel(

"

监控路径:

"

);

label.setBounds(

33

,

20

,

65

,

15

);

contentPane.add(label);

textField

=

new

JTextField(

"

D:/

"

);

textField.setBounds(

90

,

16

,

219

,

21

);

contentPane.add(textField);

textField.setColumns(

10

);

JButton button

=

new

JButton(

"

开始监控

"

);

button.addActionListener(

new

ActionListener() {

public

void

actionPerformed(ActionEvent e) {

try

{

addWatch();

}

catch

(Exception ex) {

ex.printStackTrace();

}

}

});

button.setBounds(

319

,

16

,

93

,

23

);

contentPane.add(button);

textArea

=

new

JTextArea();

JScrollPane scrollPane

=

new

JScrollPane(textArea);

scrollPane.setBounds(

33

,

45

,

480

,

207

);

contentPane.add(scrollPane);

}

public

void

addWatch()

throws

Exception {

String path

=

textField.getText();

int

mask

=

JNotify.FILE_CREATED

|

JNotify.FILE_DELETED

|

JNotify.FILE_MODIFIED

|

JNotify.FILE_RENAMED;

boolean

watchSubtree

=

true

;

//

添加文件监听

int

watchID

=

JNotify.addWatch(path, mask, watchSubtree,

new

Listener());

}

class

Listener

implements

JNotifyListener {

public

void

fileRenamed(

int

wd, String rootPath, String oldName,

String newName) {

textArea.append(

"

文件:

"

+

rootPath

+

"

:

"

+

oldName

+

"

重命名为:

"

+

newName

+

"

\n

"

);

}

public

void

fileModified(

int

wd, String rootPath, String name) {

textArea.append(

"

文件修改

"

+

rootPath

+

"

:

"

+

name

+

"

\n

"

);

}

public

void

fileDeleted(

int

wd, String rootPath, String name) {

textArea.append(

"

删除文件:

"

+

rootPath

+

"

:

"

+

name

+

"

\n

"

);

}

public

void

fileCreated(

int

wd, String rootPath, String name) {

textArea.append(

"

新建文件:

"

+

rootPath

+

"

:

"

+

name

+

"

\n

"

);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值