我正在尝试找到一种有效的方法来对大小超过String's max size的ByteArrayOutputStream进行模式匹配。
在适合单个字符串的ByteArrayOutputStream上进行模式匹配很简单:
private boolean doesStreamContainPattern(Pattern pattern, ByteArrayOutputStream baos) throws IOException {
/*
* Append external source String to output stream...
*/
if (pattern != null) {
String out = new String(baos.toByteArray(), "UTF-8");
if (pattern.matcher(out).matches()) {
return true;
}
}
/*
* Some other processing if no pattern match
*/
return false;
}
但是如果baos
的大小超过String的最大大小,问题将变成:
baos
输入多个字符串。baos
内容)。[步骤2看起来比步骤1更具挑战性,但我知道Unix sed之类的实用程序仅对文件执行此操作。
完成此任务的正确方法是什么?
您可以编写一个简单的包装器类以从流中实现CharSequence
:
class ByteArrayCharSequence implement CharSequence {
private byte[] array;
public StreamCharSequence(byte[] input) {
array = input;
}
public char charAt(int index) {
return (char) array[index];
}
public int length() {
return array.length;
}
public CharSequence subSequence(int start, int end) {
return new ByteArrayCharSequence(Arrays.copyOfRange(array, start, end));
}
public String toString() {
// maybe test whether we exceeded max String length
}
}
然后匹配依据
private boolean doesStreamContainPattern(Pattern pattern, ByteArrayOutputStream baos) throws IOException {
if (pattern != null) {
CharSequence seq = new ByteArrayCharSequence(baos.toByteArray());
if (pattern.matcher(seq).matches()) {
return true;
}
}
/*
* Some other processing if no pattern match
*/
return false;
}
[将边缘强制转换为char
并使用copyOfRange
时,边缘周围明显很粗糙,但是它在大多数情况下应该可以使用,并且可以针对那些不适合的情况进行调整。