1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.io.input;
18
19 import static org.apache.commons.io.IOUtils.EOF;
20
21 import java.io.FilterReader;
22 import java.io.IOException;
23 import java.io.Reader;
24 import java.util.function.IntPredicate;
25
26
27
28
29 public abstract class AbstractCharacterFilterReader extends FilterReader {
30
31
32
33
34
35
36 protected static final IntPredicate SKIP_NONE = ch -> false;
37
38 private final IntPredicate skip;
39
40
41
42
43
44
45 protected AbstractCharacterFilterReader(final Reader reader) {
46 this(reader, SKIP_NONE);
47 }
48
49
50
51
52
53
54
55
56 protected AbstractCharacterFilterReader(final Reader reader, final IntPredicate skip) {
57 super(reader);
58 this.skip = skip == null ? SKIP_NONE : skip;
59 }
60
61
62
63
64
65
66
67 protected boolean filter(final int ch) {
68 return skip.test(ch);
69 }
70
71 @Override
72 public int read() throws IOException {
73 int ch;
74 do {
75 ch = in.read();
76 } while (ch != EOF && filter(ch));
77 return ch;
78 }
79
80 @Override
81 public int read(final char[] cbuf, final int off, final int len) throws IOException {
82 final int read = super.read(cbuf, off, len);
83 if (read == EOF) {
84 return EOF;
85 }
86 int pos = off - 1;
87 for (int readPos = off; readPos < off + read; readPos++) {
88 if (filter(cbuf[readPos])) {
89 continue;
90 }
91 pos++;
92 if (pos < readPos) {
93 cbuf[pos] = cbuf[readPos];
94 }
95 }
96 return pos - off + 1;
97 }
98 }