/** * Copyright 1999-2009 The Pegadi Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pegadi.publisher.io; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * This is a filtered output stream that converts line separators from * <CODE>UNIX</CODE>/<CODE>MAC</CODE> * into <code>UNIX</CODE>/<CODE>MAC</CODE>/<CODE>WINDOWS</CODE> * The line separators are as follows: * <ul> * <item><code>WINDOWS</code>: <code>CRLF</code> </item> * <item><code>MAC</code>: <code>CR</code> </item> * <item><code>UNIX</code>: <code>LF</code> </item> * </ul> */ public class CRLFFilterOutputStream extends FilterOutputStream { public enum Mode {WINDOWS, UNIX, MAC, NOFILTER} public Mode mode; private transient int previous = -1; /** * Constructor taking a Writer and a mode as arguments * @param mode One of <code>UNIX</code>, <code>WINDOWS</code>, * <code>MAC</code> */ public CRLFFilterOutputStream(OutputStream out, Mode mode) { super(out); this.mode=mode; } /** * Writes a single byte while filtering it according to mode */ @Override public void write(int b) throws IOException { boolean isCRLF = previous == 13 && b == 10; boolean isCRCR = previous == 13 && b == 13; if(previous == 13){ if(mode == Mode.WINDOWS){ if(isCRLF){ out.write(13); out.write(10); previous = 10; }if(isCRCR){ out.write(13); out.write(10); out.write(13); out.write(10); previous = 10; } }else if(mode == Mode.MAC){ if(isCRLF){ out.write(10); previous = 10; }else if(isCRCR){ out.write(10); out.write(10); previous = 10; }else{ out.write(10); out.write(b); previous = b; } }else if(mode == Mode.UNIX){ if(isCRLF){ out.write(13); previous = 13; }else if(isCRCR){ out.write(13); out.write(13); previous = 13; }else { out.write(b); previous = b; } } }else if(b == 13){ previous = 13; }else if(b == 10) { if(mode == Mode.WINDOWS){ out.write(13); out.write(10); previous = 10; } else if(mode == Mode.MAC){ out.write(10); previous = 10; } else if(mode == Mode.UNIX){ out.write(13); previous = 13; } }else { out.write(b); } } /** * Writes an array of bytes while filtering it according to mode */ @Override public void write(byte[] b, int off, int len) throws IOException { for(int i=off;i<off+len;i++) { write(b[i]); } } /** * Writes an array of bytes while filtering it according to mode */ @Override public void write(byte[] b) throws IOException { for(int i=0;i<b.length;i++) { write(b[i]); } } }