LineWrapperOutputStream extends FilterOutputStream { @Override public void write(byte[] bytes, int offset, int length) throws IOException { if ((offset | length | (bytes.length - (length + offset)) | (offset + length)) < 0) { throw new IndexOutOfBoundsException(); } if (length > 0) { if (this.count + length >= this.wrapAt) { int off = offset; int len = length; int curlen = this.wrapAt - this.count; do { this.out.write(bytes, off, curlen); this.out.write(NEWLINE, 0, NEWLINE.length); off += curlen; len -= curlen; curlen = (len > this.wrapAt) ? this.wrapAt : len; } while (curlen == this.wrapAt); if (curlen > 0) { this.out.write(bytes, off, curlen); } this.count = curlen; } else { this.count += length; this.out.write(bytes, offset, length); } } } LineWrapperOutputStream(OutputStream outputStream, int wrapAt); @Override void write(byte[] bytes, int offset, int length); @Override void write(int i);  }
@Test void avoidWrapping() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LineWrapperOutputStream lwos = new LineWrapperOutputStream(baos, 10); lwos.write("12345".getBytes()); lwos.write("1234567890".getBytes(),5,4); lwos.close(); assertThat(baos.toString(), equalTo("123456789")); }
@Test void exactWrapping() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LineWrapperOutputStream lwos = new LineWrapperOutputStream(baos, 10); lwos.write("789012345".getBytes(),4,5); lwos.write("67890".getBytes()); lwos.close(); assertThat(baos.toString(), equalTo("1234567890" + NEWLINE)); }
@Test void multilineWrapping() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LineWrapperOutputStream lwos = new LineWrapperOutputStream(baos, 10); lwos.write("12345".getBytes()); lwos.write("3456789012345678".getBytes(),3,10); lwos.write("6789012345".getBytes(),0,7); lwos.close(); assertThat(baos.toString(), equalTo("1234567890" + NEWLINE + "1234567890" + NEWLINE + "12")); }
@Test void onByteWrapping() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LineWrapperOutputStream lwos = new LineWrapperOutputStream(baos, 10); lwos.write("123456789".getBytes()); lwos.write("0".getBytes()[0]); lwos.write("12345".getBytes()); lwos.close(); assertThat(baos.toString(), equalTo("1234567890" + NEWLINE + "12345")); }