CommentNewlineOutputStream extends FilterOutputStream { public void write(int i) throws IOException { if (i == '\r') { out.write(newline); } else if (i == '\n') { if (lastByte != '\r') { out.write(newline); } } else if (i == '\0') { out.write('\n'); } else { out.write(i); } lastByte = i; } CommentNewlineOutputStream(OutputStream out); void write(int i); void write(byte[] buf); void write(byte buf[], int off, int len); void writeln();  }
@Test public void testWriter() throws IOException { String lines = "one\ntwo\nthree\rfour\r\n"; String expect = "one\\ntwo\\nthree\\nfour\\n"; InputStream in = new ByteArrayInputStream(lines.getBytes()); ByteArrayOutputStream bya = new ByteArrayOutputStream(); CommentNewlineOutputStream out = new CommentNewlineOutputStream(bya); Writer outWriter = new BufferedWriter(new OutputStreamWriter(out)); outWriter.write(lines); outWriter.close(); String actual = bya.toString(); assertEquals(expect, actual); }