如何“修改”InputStream?我有一个文件作为输入,我想修改一些变量并转发一个新的InputStream。
例如,初始InputStream包含Hello ${var}。然后,我想用var =“InputStream”“修改”这个世界,生成一个InputStream Hello world。
执行此操作的最佳实践是什么?谢谢。
发布于 2010-07-15 21:56:30
java.io是一个完整的decorator pattern。利用它,创建一个extends InputStream的类(可能是DataInputStream或者更好的,一些Reader,因为你真正感兴趣的是字符,而不是字节,而是ala),添加一个构造函数,它接受原始的InputStream并覆盖read()方法来读取原始流,在一定程度上缓冲它(例如,从${到firstnext }),然后确定键并返回修改后的数据。
如果您调用新类FormattedInputStream或更多,那么您可以将new FormattedInputStream(originalInputStream)返回给最终用户,让最终用户仍然只需将其分配并用作InputStream即可。
发布于 2010-07-15 22:25:02
您可以尝试对FilterInputStream进行子类化。
从文档中:
FilterInputStream包含一些其他输入流,它将其用作基本的数据源,可能会在的过程中转换数据或提供其他功能。类FilterInputStream本身只是使用将所有请求传递到所包含的输入流的版本来覆盖InputStream的所有方法。FilterInputStream的子类可以进一步覆盖这些方法中的一些方法,还可以提供其他方法和字段。
这里是它的初步尝试。不是解决这个问题的最好方法。您可能希望覆盖更多的方法,也许可以使用阅读器。(或者甚至可以使用Scanner逐行处理文件。)
import java.io.*;
import java.util.*;
public class Test {
public static void main(String args[]) throws IOException {
String str = "Hello world, this is the value one ${bar} and this " +
"is the value two ${foo}";
// The "original" input stream could just as well be a FileInputStream.
InputStream someInputStream = new StringBufferInputStream(str);
InputStream modified = new SubstitutionStream(someInputStream);
int c;
while ((c = modified.read()) != -1)
System.out.print((char) c);
modified.close();
}
}
class SubstitutionStream extends FilterInputStream {
Map<String, String> valuation = new HashMap<String, String>() {{
put("foo", "123");
put("bar", "789");
}};
public SubstitutionStream(InputStream src) {
super(src);
}
LinkedList<Character> buf = new LinkedList<Character>();
public int read() throws IOException {
if (!buf.isEmpty())
return buf.remove();
int c = super.read();
if (c != '$')
return c;
int c2 = super.read();
if (c2 == '{') {
StringBuffer varId = new StringBuffer();
while ((c2 = super.read()) != '}')
varId.append((char) c2);
for (char vc : valuation.get(varId.toString()).toCharArray())
buf.add(vc);
return buf.remove();
} else {
buf.add((char) c2);
return c;
}
}
}输出:
Hello world, this is the value one 789 and this is the value two 123发布于 2012-06-29 22:12:33
您可以使用Streamflyer,它支持开箱即用的字符流中的文本替换。
https://stackoverflow.com/questions/3256161
复制相似问题