通过对其应用正则表达式来更改InputStream [英] Change InputStream by applying regex on it
问题描述
我有一个从Internet下载的InputStream.而且我需要在其上应用正则表达式-以便将所有出现的该正则表达式都更改为字符串,并提供. 我需要一个InputStream作为返回值,因为它应该转发到api.
I have an InputStream downloaded from the internet. And I need to apply regex on it - so that all occurrences of that regex would be changed to string, wich is provided. I need an InputStream as a return value since it should be forwarded to api.
基本上,这样的签名是最好的:
Basically, such signature would be the best:
InputStream applyRegex(InputStream stream, Pattern pattern, String changeString){
...
}
我对使用流非常了解,请尽可能以方法形式给出答案.
I have very basic knowledge of working with streams, please give an answer in method form, if it is possible.
顺便说一下,我收到的输入流的大小为0,直到调用方法read(byte [])
By the way, input stream I receive has size 0, until I call method read(byte[])
推荐答案
设法使其与github.com/rwitzel/streamflyer库一起使用. 如果有app.gradle,我们有:
Managed to get it working with github.com/rwitzel/streamflyer library. if app.gradle we have:
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;
}
}
这篇关于通过对其应用正则表达式来更改InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!