@ Override public void write ( char [ ] cbuf , int off , int len ) throws IOException { if ( len <= 0 ) { return ; } // if we havn't last seen a newline, and don't get a CR, insert a newline. if ( charsSinceNewline > 0 ) { if ( cbuf [ off ] != CARRIAGE_RETURN ) { super . write ( NEWLINEC , 0 , NEWLINEC . length ) ; charsSinceNewline = 0 ; } else { // length of this line: int nonnl = countNonNewline ( cbuf , off + 1 , len - 1 ) ; // clear the existing chars. if ( nonnl < charsSinceNewline ) { super . write ( CARRIAGE_RETURN ) ; while ( charsSinceNewline > 0 ) { final int n = Math . min ( charsSinceNewline , WHITESPACE . length ( ) ) ; super . write ( WHITESPACE , 0 , n ) ; charsSinceNewline -= n ; } } else { charsSinceNewline = 0 ; } } } charsSinceNewline = tailingNonNewline ( cbuf , off , len ) ; super . write ( cbuf , off , len ) ; flush ( ) ; }
Writer that keeps track of when it hasn t seen a newline yet will auto - insert newlines except when lines start with a carriage return .