推广 热搜: page  关键词  红书  链接  搜索  获取  哪些  数据  数据分析  服务 

java开源组件jNotify实现文件监控

   日期:2025-01-02     作者:tx2jh    caijiyuan   评论:0    移动:https://sicmodule.kub2b.com/mobile/news/14881.html
核心提示:[url]http://hi.baidu.com/wzwahl36/item/591030c630da7a66f7c95d98[/url] java本身不能直接监听系统的文件操作事件,不过
[url]http://hi.baidu.com/wzwahl36/item/591030c630da7a66f7c95d98[/url]
java本身不能直接监听系统的文件操作事件,不过可以先编写C/C++调用操作系统的API监听文件,再通过jni调用的方式实现。限于本人的C /C++水平有限,没有用C/C++实现该接口,而且已有开源组件JNotify实现了这个功能,本文例子使用JNotify。



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 + " ");

}



public void fileModified(int wd, String rootPath, String name) {

textarea.append("文件修改 " + rootPath + " : " + name + " ");

}



public void fileDeleted(int wd, String rootPath, String name) {

textarea.append("删除文件" + rootPath + " : " + name + " ");

}



public void fileCreated(int wd, String rootPath, String name) {

textarea.append("新建文件: " + rootPath + " : " + name + " ");

}

}
本文地址:https://sicmodule.kub2b.com/news/14881.html     企库往 https://sicmodule.kub2b.com/ , 查看更多

特别提示:本信息由相关用户自行提供,真实性未证实,仅供参考。请谨慎采用,风险自负。

 
 
更多>同类最新资讯
0相关评论

文章列表
相关文章
最新动态
推荐图文
最新资讯
点击排行
网站首页  |  关于我们  |  联系方式  |  使用协议  |  版权隐私  |  网站地图  |  排名推广  |  广告服务  |  积分换礼  |  网站留言  |  RSS订阅  |  违规举报  |  鄂ICP备2020018471号