View Javadoc

1   package de.matthias_burbach.mosaique.core.util;
2   
3   import java.io.BufferedWriter;
4   import java.io.FileWriter;
5   import java.io.IOException;
6   import java.io.PrintWriter;
7   import java.util.ArrayList;
8   import java.util.List;
9   
10  /***
11   * Is a log implementation which keeps lines buffered in an internal memory
12   * buffer until they are requested to be written to a file.
13   *
14   * @author Matthias Burbach
15   */
16  public class LineBufferLog implements Log {
17      /***
18       * The buffer of lines as a list of Strings each being a logged line.
19       */
20      private List buffer = new ArrayList();
21  
22      /*(non-Javadoc)
23       * @see de.matthias_burbach.mosaique.core.Log#log(
24       *          java.lang.String, java.lang.String)
25       */
26      /***
27       * {@inheritDoc}
28       */
29      public void log(final String severity, final String message) {
30          buffer.add("[" + severity + "] " + message);
31      }
32  
33      /***
34       * Writes the lines logged so far to a file. Lines logged will be deleted
35       * from the internal buffer.
36       *
37       * @param fileName The absolute path and name of the file to write to.
38       */
39      public void writeToFile(final String fileName) {
40          PrintWriter printWriter = null;
41          try {
42              printWriter =
43                  new PrintWriter(
44                          new BufferedWriter(new FileWriter(fileName, false)));
45              for (int i = 0; i < buffer.size(); i++) {
46                  String line = (String) buffer.get(i);
47                  printWriter.println(line);
48              }
49              buffer.clear();
50          } catch (IOException e) {
51             e.printStackTrace();
52          } finally {
53              if (printWriter != null) {
54                  try {
55                      printWriter.close();
56                  } catch (Exception e) {
57                      e.printStackTrace();
58                  }
59              }
60          }
61      }
62  }