通过在其上应用正则表达式来更改 InputStream

Change InputStream by applying regex on it

我有一个从 Internet 下载的 InputStream。我需要在其上应用正则表达式 - 以便该正则表达式的所有出现都将更改为提供的字符串。 我需要一个 InputStream 作为 return 值,因为它应该被转发到 api.

基本上这样的签名最好:

InputStream applyRegex(InputStream stream, Pattern pattern, String changeString){
    ...
}

我对使用流有非常基本的了解,如果可能的话,请以方法形式给出答案。

顺便说一句,我收到的输入流的大小为 0,直到我调用方法 read(byte[])

设法让它与 github.com/rwitzel/streamflyer 库一起工作。 如果 app.gradle 我们有:

compile 'com.github.rwitzel.streamflyer:streamflyer-core:1.2.0';

示例:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;

import com.github.rwitzel.streamflyer.core.ModifyingReader;
import com.github.rwitzel.streamflyer.regex.RegexModifier;

public class InputStreamModifiedWithRegex {
    private static final Charset ENCODE_CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException {
        InputStream input = IOUtils.toInputStream("AB CD EF");
        InputStream updatedInput = applyRegex(input, "[A-C]", "Z");
        System.out.println(IOUtils.toString(updatedInput, ENCODE_CHARSET));
    }

    private static InputStream applyRegex(InputStream inputStream, String pattern, String changeString)
            throws UnsupportedEncodingException {
        Reader originalReader = new InputStreamReader(inputStream, ENCODE_CHARSET);
        Reader modifyingReader = new ModifyingReader(originalReader, new RegexModifier(pattern, 0, changeString));
        inputStream = new ReaderInputStream(modifyingReader, ENCODE_CHARSET);

        return inputStream;
    }
}