1 /* Copyright (c) 2008 Sascha Kohlmann
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU Affero General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Affero General Public License for more details.
12 *
13 * You should have received a copy of the GNU Affero General Public License
14 */
15 package net.sf.eos.io;
16
17 import java.io.FilterWriter;
18 import java.io.IOException;
19 import java.io.Writer;
20
21 /**
22 * The implementation replaces linefeed (ASCII {@literal 0x0a}) and carriage
23 * return (ASCII {@literal 0x0d}) characters thru a space character
24 * (ASCII {@literal 0x20}).
25 * @author Sascha Kohlmann
26 */
27 public class NewlineReplaceWriter extends FilterWriter {
28
29 /**
30 * Creates a new writer.
31 * @param out a writer to decorate
32 */
33 public NewlineReplaceWriter(final Writer out) {
34 super(out);
35 }
36
37 /*
38 * @see java.io.FilterWriter#write(int)
39 */
40 @Override
41 public void write(final int c) throws IOException {
42 if (c == '\n' || c == '\r') {
43 this.out.write(' ');
44 } else {
45 this.out.write(c);
46 }
47 }
48
49 /*
50 * @see java.io.FilterWriter#write(char[], int, int)
51 */
52 @Override
53 public void write(final char cbuf[],
54 final int off,
55 final int len) throws IOException {
56 final char[] nbuf = new char[len];
57
58 for (int i = 0, j = off; i < len; j++, i++) {
59 char c = cbuf[j];
60 if (c == '\n' || c == '\r') {
61 c = ' ';
62 }
63 nbuf[i] = c;
64 }
65 this.out.write(nbuf, 0, nbuf.length);
66 }
67
68 /*
69 * @see java.io.FilterWriter#write(java.lang.String, int, int)
70 */
71 @Override
72 public void write(final String str,
73 final int off,
74 final int len) throws IOException {
75 final String sub = str.substring(off, (off+ len));
76 final char[] cs = sub.toCharArray();
77 write(cs, 0, cs.length);
78 }
79 }