View Javadoc

1   package org.astrogrid.io.ascii;
2   
3   /***
4    * Description: ASCII Output stream.  Includes various methods for
5    * writing out numbers, text, etc to an ASCII text file
6    *
7    * @author           : M Hill
8    *
9    **/
10  import java.io.*;
11  
12  public class AsciiOutputStream extends FilterOutputStream implements AsciiCodes
13  {
14     
15     /***
16      * Standard FilterStream-type constructor. .
17      * @param out java.io.OutputStream
18      */
19     public AsciiOutputStream(java.io.OutputStream out)
20     {
21        super(out);
22     }
23  
24     /***
25      * prefixes any of the given occurences of character 'findChar' with "//" and replaces
26      * with the second character so that they get interpreted as literals rather than
27      * special codes.
28      *
29      **/
30     private void escape(StringBuffer b, char findChar, char replaceChar)
31     {
32        for(int i = 0; i < b.length(); i++) {
33           if (b.charAt(i) == findChar) {
34              b.insert(i++,'//');
35              b.setCharAt(i++, replaceChar);
36           }
37        }
38     }
39     /***
40      * Wraps string representation of given object x in quotes, and ensures that any
41      * 'odd' characters within it - such as other quotes - are 'escaped' so they are
42      * interpreted correctly when re-read.
43      */
44     public String quoteWrap(Object x)
45     {
46        StringBuffer sb = new StringBuffer(x.toString());
47        escape(sb, '"', '"');
48        escape(sb, '\n', 'n');
49        escape(sb, '\r', 'r');
50        return "" + QUOTE + sb + QUOTE;
51     }
52  
53     /***
54      * Writes the given string
55      */
56     public void write(String s) throws IOException
57     {
58        if (s == null) return;
59        
60        write(s.getBytes());
61     }
62  
63     /***
64      * Writes out a 'real' number in ASCII form.
65      */
66     public void write(double r) throws IOException
67     {
68        write(Double.toString(r));
69     }
70  
71     /***
72      * Writes out an integer number in ASCII form.
73      */
74     public void write(long i) throws IOException
75     {
76        write(Long.toString(i));
77     }
78      
79      /***
80       * Writes a line
81       */
82      public void writeLine(String s) throws IOException
83      {
84          write(s);
85          write(NL);
86      }
87  }
88  
89