gpt4 book ai didi

java - 在 InputStream 中过滤(搜索和替换)字节数组

转载 作者:太空狗 更新时间:2023-10-29 22:31:45 31 4
gpt4 key购买 nike

我有一个 InputStream,它将 html 文件作为输入参数。我必须从输入流中获取字节。

我有一个字符串:"XYZ"。我想将这个字符串转换为字节格式,并检查我从 InputStream 获得的字节序列中是否有匹配的字符串。如果有的话,我必须将匹配项替换为其他字符串的 bye 序列。

有人可以帮我解决这个问题吗?我使用正则表达式查找和替换。但是,我不知道如何查找和替换字节流。

以前,我使用 jsoup 来解析 html 并替换字符串,但是由于一些 utf 编码问题,当我这样做时文件似乎已损坏。

TL;DR:我的问题是:

是否有一种方法可以在 Java 中的原始 InputStream 中查找和替换字节格式的字符串?

最佳答案

不确定您是否选择了解决问题的最佳方法。

就是说,我不喜欢(并且有政策不)用“不要”回答问题,所以这里是...

看看FilterInputStream .

来自文档:

A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.


把它写下来是一个有趣的练习。这是一个完整的例子:

import java.io.*;
import java.util.*;

class ReplacingInputStream extends FilterInputStream {

LinkedList<Integer> inQueue = new LinkedList<Integer>();
LinkedList<Integer> outQueue = new LinkedList<Integer>();
final byte[] search, replacement;

protected ReplacingInputStream(InputStream in,
byte[] search,
byte[] replacement) {
super(in);
this.search = search;
this.replacement = replacement;
}

private boolean isMatchFound() {
Iterator<Integer> inIter = inQueue.iterator();
for (int i = 0; i < search.length; i++)
if (!inIter.hasNext() || search[i] != inIter.next())
return false;
return true;
}

private void readAhead() throws IOException {
// Work up some look-ahead.
while (inQueue.size() < search.length) {
int next = super.read();
inQueue.offer(next);
if (next == -1)
break;
}
}

@Override
public int read() throws IOException {
// Next byte already determined.
if (outQueue.isEmpty()) {
readAhead();

if (isMatchFound()) {
for (int i = 0; i < search.length; i++)
inQueue.remove();

for (byte b : replacement)
outQueue.offer((int) b);
} else
outQueue.add(inQueue.remove());
}

return outQueue.remove();
}

// TODO: Override the other read methods.
}

示例用法

class Test {
public static void main(String[] args) throws Exception {

byte[] bytes = "hello xyz world.".getBytes("UTF-8");

ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

byte[] search = "xyz".getBytes("UTF-8");
byte[] replacement = "abc".getBytes("UTF-8");

InputStream ris = new ReplacingInputStream(bis, search, replacement);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

int b;
while (-1 != (b = ris.read()))
bos.write(b);

System.out.println(new String(bos.toByteArray()));

}
}

给定字符串 "Hello xyz world" 的字节,它打印:

Hello abc world

关于java - 在 InputStream 中过滤(搜索和替换)字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7743534/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com