我使用以下格式化程序:
protected static final ThreadLocal<Formatter> textFormatter = new ThreadLocal<Formatter>() {
@Override
protected Formatter initialValue() {
return new Formatter();
}
};
我在一种方法中使用这种格式化程序:
final String firstValue = textFormatter.get().format("%s and %s", "a","b");
final String secondValue = textFormatter.get().format("%s and %s", "c","d");
我希望firstValue成为&#34; a和b&#34;和secondValue =&#34; c和d&#34;但是secondValue =&#34; a和bc以及d&#34;。因此保留旧值并将其附加到secondValue。有没有办法清除格式化程序?
答案 0 :(得分:0)
initialValue()一次
这意味着你只能在
上面的两行中获得一个Formatter对象,因为Formatter.format方法将格式化的字符串写入Formatter对象的目标(Formatter方法中的内部缓冲区)
然后,因为你使它等于String,java将自动调用格式化程序上的toString()。
因此,第一次toString将写入正确内容的缓冲区内容&#34; a和b&#34;
但是第二次它会写出完整的缓冲区,因为你没有刷新缓冲区&#34; a和bc以及d&#34;
修复很容易
final String firstValue = textFormatter.get().format("%s and %s", "a","b");
textFormatter.get().flush();
final String secondValue = textFormatter.get().format("%s and %s", "c","d");
textFormatter.get().flush();