欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 监听文件或文件夹变化

程序员文章站 2023-04-05 09:31:24
今天遇到一个新需求,当从服务器下载文件后用指定的本地程序打开,不知道何时文件下载完成,只能考虑监听文件夹,当有新文件创建的时候打开指定程序。 在此给出一个完整的下载和打开过程: 1、下载文件 jsp页面 java代码 2、监听文件夹,执行打开程序 1 package demo; 2 3 import ......

    今天遇到一个新需求,当从服务器下载文件后用指定的本地程序打开,不知道何时文件下载完成,只能考虑监听文件夹,当有新文件创建的时候打开指定程序。

在此给出一个完整的下载和打开过程:

1、下载文件

jsp页面

1 <body>
2     <div>
3         <a href="<%=basepath%>/user/downloadfile?filename=proplan.dwg" >点击下载</a>
4     </div>
5 </body>

java代码

 1  public static void downloadtfile(httpservletresponse response, file file) throws ioexception
 2     {
 3         response.reset();
 4         response.setcontenttype("application/vnd.ms-excel;charset=utf-8");
 5         response.setheader("content-disposition",
 6                 "attachment; filename=" + new string(file.getname().getbytes(), "iso-8859-1"));
 7         outputstream outputstream = response.getoutputstream();
 8         inputstream in = new fileinputstream(file);
 9         byte[] b = new byte[1024];
10         int len = 0;
11         while ((len = in.read(b)) > 0)
12         {
13             outputstream.write(b, 0, len);
14         }
15         outputstream.write(b);
16         outputstream.flush();
17         in.close();
18     }

2、监听文件夹,执行打开程序

 1 package demo;
 2 
 3 import java.io.ioexception;
 4 import java.nio.file.filesystems;
 5 import java.nio.file.path;
 6 import java.nio.file.paths;
 7 import java.nio.file.standardwatcheventkinds;
 8 import java.nio.file.watchevent;
 9 import java.nio.file.watchkey;
10 import java.nio.file.watchservice;
11 import java.util.list;
12 import java.util.concurrent.executorservice;
13 import java.util.concurrent.executors;
14 
15 public class folderlistener {
16     private static executorservice fixedthreadpool = executors.newcachedthreadpool();
17     private watchservice ws;
18     private string listenerpath;
19     private folderlistener(string path) {
20         try {
21             ws = filesystems.getdefault().newwatchservice();
22             this.listenerpath = path;
23             start();
24         } catch (ioexception e) {
25             e.printstacktrace();
26         }
27     }
28 
29     private void start() {
30         fixedthreadpool.execute(new listner(ws,this.listenerpath));
31     }
32 
33     public static void addlistener(string path) throws ioexception {
34         folderlistener resourcelistener = new folderlistener(path);
35         path p = paths.get(path);
36         //注册监听事件,文件的修改、删除和创建
37         p.register(resourcelistener.ws,
38             standardwatcheventkinds.entry_modify,
39             standardwatcheventkinds.entry_delete,
40             standardwatcheventkinds.entry_create);
41     }
42     
43 
44     public static void main(string[] args) throws ioexception {
45         //监听下载目录的变化
46         folderlistener.addlistener("c:\\users\\administrator\\downloads\\");
47     }
48 }
49 
50 class listner implements runnable {
51     private watchservice service;
52     private string rootpath;
53     
54     public listner(watchservice service,string rootpath) {
55         this.service = service;
56         this.rootpath = rootpath;
57     }
58 
59     public void run() {
60         try {
61             while(true){
62                 watchkey watchkey = service.take();
63                 list<watchevent<?>> watchevents = watchkey.pollevents();
64                 for(watchevent<?> event : watchevents){
65                     if(event.context().tostring().endswith(".dwg"))
66                     // 根据事件类型采取不同的操作。。。。。。。
67                     try {
68                         system.out.println("["+rootpath+event.context()+"]文件发生了["+event.kind()+"]事件"+    event.count());  
69                         string[] cmd = { "d:\\cad\\autocad\\acad.exe", "c:\\users\\administrator\\downloads\\" + event.context().tostring() };
70                         runtime.getruntime().exec(cmd);
71                     } catch (ioexception e) {
72                         e.printstacktrace();
73                     }
74                 }
75                 watchkey.reset();
76             }
77         } catch (interruptedexception e) {
78             e.printstacktrace();
79         }finally{
80             system.out.println("fdsfsdf");
81             try {
82                 service.close();
83             } catch (ioexception e) {
84                 e.printstacktrace();
85             }
86         }
87         
88     }
89 }

 

补充,除了执行指定exe,打开软件外还可以执行命令行

 1 package demo;
 2 
 3 import java.io.bufferedreader;
 4 import java.io.inputstream;
 5 import java.io.inputstreamreader;  
 6   
 7 public class command {  
 8     
 9     public static void main(string[] args) {
10         string s = execmd("ipconfig");
11         system.out.println(s);
12     }
13     
14     public static string execmd(string commandstr) {  
15         bufferedreader br = null;  
16         stringbuilder sb = new stringbuilder(); 
17         try {  
18             process p = runtime.getruntime().exec(commandstr);  
19             br = new bufferedreader(new inputstreamreader(p.getinputstream(), "gb2312"));
20 //            inputstream in = p.getinputstream();
21 //            byte[] b = new byte[1024];
22 //            int len = 0;
23 //            while((len = in.read(b)) > 0){
24 //                sb.append(new string(b,"gb2312")).append("\n");
25 //            }
26             string line = null;  
27             while ((line = br.readline()) != null) {  
28                 sb.append(line).append("\n");  
29             }  
30         } catch (exception e) {  
31             e.printstacktrace();  
32         }   
33         finally  
34         {  
35             if (br != null)  
36             {  
37                 try {  
38                     br.close();  
39                 } catch (exception e) {  
40                     e.printstacktrace();  
41                 }  
42             }  
43         }  
44         return sb.tostring();
45     }  
46 }