Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 6 of 6
1: import java.io.FileReader;
2: import java.io.LineNumberReader;
3:
4: public class Test {
5: public static void main(String args[]) {
6: if(args.length < 1) {
7: System.err.println("Usage: " + "java Test filename");
8: System.exit(1);
9: }
10: new Test(args[0]);
11: }
12: public Test(String filename) {
13: try {
14: FileReader frdr = new FileReader(filename);
15: LineNumberReader lrdr = new LineNumberReader(frdr);
16:
17: for(String line; (line = lrdr.readLine()) != null;) {
18: System.out.print(lrdr.getLineNumber() + ":\t");
19: printLine(line);
20: }
21: }
22: catch(java.io.FileNotFoundException fnfx) {
23: fnfx.printStackTrace();
24: }
25: catch(java.io.IOException iox) {
26: iox.printStackTrace();
27: }
28: }
29: private void printLine(String s) {
30: for(int c, i=0; i < s.length(); ++i) {
31: c = s.charAt(i);
32:
33: if(c == '\t') System.out.print(" ");
34: else System.out.print((char)c);
35: }
36: System.out.println();
37: }
38: }
Notice how I've constructed the line reader used in Example 3:
FileReader frdr = new FileReader(filename); LineNumberReader lrdr = new LineNumberReader(frdr);
The LineNumberReader decorator encloses another reader; in this case, the enclosed reader is an instance of FileReader. The line number reader forwards method calls, such as read(), to its enclosed reader and tracks line numbers, which can be accessed with LineNumberReader.getLineNumber(). Because LineNumberReader is a decorator, you can easily track line numbers for any type of reader.
In this article I provided an overview of design patterns, but in the process I may have created as many questions as I've answered. For example, although I demonstrated how to use three popular design patterns, I did not show you how to implement those patterns. In subsequent articles, I will discuss many of the design patterns from the GOF book in detail, including the best uses for those patterns, and how they are used and implemented.
If you look at the reader classes in java.io, you will find another decorator: BufferedReader. That class buffers reads, making it more efficient than an unbuffered reader. In light of this new discovery, you might
decide to make Example 3 more efficient, like this:
FileReader frdr = new FileReader(filename); BufferedReader brdr = new BufferedReader(frdr); // "mix in" a buffered reader LineNumberReader lrdr = new LineNumberReader(brdr);
Answer the following questions:
Read more about Core Java in JavaWorld's Core Java section.