KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > mail > util > CRLFOutputStream


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the "License"). You may not use this file except
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * HEADER in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21
22 /*
23  * @(#)CRLFOutputStream.java 1.11 05/08/29
24  *
25  * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
26  */

27
28 package com.sun.mail.util;
29
30 import java.io.*;
31
32
33 /**
34  * Convert lines into the canonical format, that is, terminate lines with the
35  * CRLF sequence.
36  *
37  * @author John Mani
38  */

39 public class CRLFOutputStream extends FilterOutputStream {
40     protected int lastb = -1;
41     protected static byte[] newline;
42     static {
43     newline = new byte[2];
44     newline[0] = (byte)'\r';
45     newline[1] = (byte)'\n';
46     }
47
48     public CRLFOutputStream(OutputStream os) {
49     super(os);
50     }
51
52     public void write(int b) throws IOException {
53     if (b == '\r') {
54         out.write(newline);
55     } else if (b == '\n') {
56         if (lastb != '\r')
57         out.write(newline);
58     } else {
59         out.write(b);
60     }
61     lastb = b;
62     }
63
64     public void write(byte b[]) throws IOException {
65     write(b, 0, b.length);
66     }
67
68     public void write(byte b[], int off, int len) throws IOException {
69     int start = off;
70     
71     len += off;
72     for (int i = start; i < len ; i++) {
73         if (b[i] == '\r') {
74         out.write(b, start, i - start);
75         out.write(newline);
76         start = i + 1;
77         } else if (b[i] == '\n') {
78         if (lastb != '\r') {
79             out.write(b, start, i - start);
80             out.write(newline);
81         }
82         start = i + 1;
83         }
84         lastb = b[i];
85     }
86     if ((len - start) > 0)
87         out.write(b, start, len - start);
88     }
89
90     /*
91      * Just write out a new line, something similar to out.println()
92      */

93     public void writeln() throws IOException {
94         out.write(newline);
95     }
96 }
97
Popular Tags