/Users/lyon/j4p/src/classUtils/pack/util/AutoCRWriter.java

1    package classUtils.pack.util; 
2     
3    import java.io.*; 
4     
5    /** 
6     * A class that automatically intercepts and prints line separators 
7     * without explicitly needing for println() to be called (behaves 
8     * as PrintStream rather than PrintWriter. 
9     */ 
10   public class AutoCRWriter extends Writer { 
11    
12       private static char[] lineSep; 
13       private PrintWriter out; 
14       private int index=0; 
15    
16       public AutoCRWriter(Writer out) { 
17           if (out instanceof PrintWriter) this.out=(PrintWriter)out; 
18           else this.out=new PrintWriter(out); 
19       } 
20    
21       public AutoCRWriter(OutputStream out) { 
22           this.out=new PrintWriter(new OutputStreamWriter(out)); 
23       } 
24    
25       public void write(int c) throws IOException { 
26    
27           //System.out.println("C="+c); 
28    
29           if (c==lineSep[index]) { 
30               if (++index == lineSep.length) { 
31                   out.flush(); 
32                   out.println(); 
33                   index=0; 
34                   return; 
35               } 
36           } else { 
37               if (index != 0) { 
38                   for(int i=0; i < index; i++) 
39                       out.write(lineSep[i]); 
40                   index=0; 
41               } 
42               out.write(c); 
43           } 
44       } 
45    
46       public void close() throws IOException { 
47           if (index != 0) { 
48               for(int i=0; i < index; i++) 
49                   out.write(lineSep[i]); 
50               index=0; 
51           } 
52           out.close(); 
53       } 
54    
55       public void flush() throws IOException { 
56           if (index != 0) { 
57               for(int i=0; i < index; i++) 
58                   out.write(lineSep[i]); 
59               index=0; 
60           } 
61           out.flush(); 
62       } 
63    
64       public void write(char[] cbuf, int off, int len) throws IOException { 
65           for(int i=off;i<off+len;i++) 
66               write((int)cbuf[i]); 
67       } 
68    
69       static { 
70            String s = System.getProperty("line.separator"); 
71            lineSep = new char[s.length()]; 
72            for(int i=0;i<lineSep.length;i++) lineSep[i]=s.charAt(i); 
73       } 
74    
75    
76       public static void main(String args[]) throws IOException { 
77           Writer w = new PrintWriter(new AutoCRWriter(System.out)); 
78           w.write("Hello"); 
79           w.write(new String(lineSep)); 
80           w.write("World"); 
81           w.write(new String(lineSep)); 
82           //w.flush(); 
83    
84           ((PrintWriter)w).print("Hello2"); 
85           ((PrintWriter)w).println(); 
86           ((PrintWriter)w).print("World2"); 
87           ((PrintWriter)w).println(); 
88       } 
89    
90   } 
91    
92