Java Reference
In-Depth Information
5.
6. private PrintWriter out;
7.
8. public MyErrorLog(String fileName) {
9. try {
10. out = new PrintWriter(new FileWriter(fileName));
11. }catch(IOException e) {
12. e.printStackTrace();
13. }
14. }
15.
16. public void logErrors(Date timeStamp, String... errors) {
17. out.print(timeStamp + “:”);
18. for(String error : errors) {
19. out.print(error + “, “);
20. }
21. out.println();
22. out.flush();
23. }
24.
25. public void finalize() {
26. out.close();
27. }
28.
29. public static void main(String [] args) {
30. Date now = new Date();
31. MyErrorLog m = new MyErrorLog(“errors.txt”);
32. m.logErrors(now);
33. m.logErrors(now, “Problem #1”);
34. m.logErrors(now, “a”, “b”, “c”, “d”, “e”, “f”);
35. String [] array = {“does”, “this”, “work?”};
36. m.logErrors(now, array);
37. }
38.}
The new MyErrorLog statement on line 31 invokes the constructor on line 8, which
creates a new text fi le named errors.txt for writing to. The logErrors method is invoked
four times, and after running this program the errors.txt fi le looks something like this:
Tue Aug 04 14:32:56 MDT 2009:
Tue Aug 04 14:32:56 MDT 2009:Problem #1,
Tue Aug 04 14:32:56 MDT 2009:a, b, c, d, e, f,
Tue Aug 04 14:32:56 MDT 2009:does, this, work?,
Search WWH ::




Custom Search