java 监听文件或文件夹变化

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

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

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 }
View Code

 

补充,除了执行指定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 }  

 

posted on 2019-09-25 18:25  壹佰  阅读(4508)  评论(0编辑  收藏  举报

导航