java listens for file or folder changes

Posted by Cless on Tue, 08 Oct 2019 04:07:21 +0200

Today, we meet a new requirement. When downloading files from the server, we open them with the designated local program. We don't know when the file download is completed. We can only consider listening folders and opening the designated program when new files are created.

Here is a complete download and opening process:

1. Download files

jsp page

1 <body>
2     <div>
3         <a href="<%=basePath%>/user/downLoadFile?fileName=proPlan.DWG" >Click to download</a>
4     </div>
5 </body>

java code

 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. Monitor folders and execute open programs

 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         //Register to listen for events, modify, delete, and create files
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         //Monitor changes in download directories
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                     // Different actions are taken depending on the type of event...
67                     try {
68                         System.out.println("["+rootPath+event.context()+"]The file happened.["+event.kind()+"]Event"+    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 }

 

Plus, besides executing the specified exe, opening the software can also execute the command line

 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 }  

Topics: Java JSP Excel