KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > tracelog > listeners > FileListener


1 /*
2  * FileListener.java May 8, 2007
3  */

4 package net.sourceforge.tracelog.listeners;
5
6 import java.io.BufferedReader JavaDoc;
7 import java.io.DataInputStream JavaDoc;
8 import java.io.FileInputStream JavaDoc;
9 import java.io.FileNotFoundException JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStreamReader JavaDoc;
12
13 public class FileListener implements Runnable JavaDoc {
14     private String JavaDoc logPath;
15     private LogViewerHandler logRepository;
16
17     public FileListener(LogViewerHandler logRepository, String JavaDoc logPath) {
18         this.logPath = logPath;
19         this.logRepository = logRepository;
20     }
21
22     /**
23      * "Forwards" the log contents to the last line and displays any recent log
24      * messages into the log viewer.
25      *
26      * @see java.lang.Runnable#run()
27      */

28     public void run() {
29         BufferedReader JavaDoc br = null;
30         String JavaDoc line = null;
31
32         try {
33             br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(new DataInputStream JavaDoc(new FileInputStream JavaDoc(logPath))));
34
35             // "forward" to the last log contents
36
while ((line = br.readLine()) != null) {
37             }
38
39             // prepares to write incoming log contents
40
logRepository.write("Listening on " + logPath + "...");
41
42             while (!Thread.interrupted()) {
43                 try {
44                     line = br.readLine();
45                 }
46                 // exception may occur if the tool cannot access the file
47
// because another process has locked a portion of the file.
48
// When this happens, then make sure to put the thread to sleep
49
// then try it again later.
50
catch (IOException JavaDoc e) {
51                     line = null;
52                 }
53
54                 if (line == null) {
55                     Thread.sleep(1000);
56                 }
57                 else {
58                     logRepository.write(line);
59                 }
60             }
61         }
62         catch (InterruptedException JavaDoc ignored) {
63             logRepository.write("Stopping log... done.");
64         }
65         catch (FileNotFoundException JavaDoc e) {
66             logRepository.write("ERROR: Log file not found: " + logPath);
67             logRepository.write("ERROR: Please make sure this log path is correct and you have enough privilege to access this log path.");
68         }
69         catch (Exception JavaDoc e) {
70             e.printStackTrace();
71         }
72         finally {
73             try {
74                 br.close();
75             }
76             catch (Exception JavaDoc ignored) {
77             }
78         }
79     }
80 }
81
Popular Tags