我的用例是能够在不创建文件的情况下创建FileOutputStream.所以我创建了这个基于Guava的OutputStream:
public class LazyInitOutputStream extends OutputStream {
private final Supplier<OutputStream> lazyInitOutputStreamSupplier;
public LazyInitOutputStream(Supplier<OutputStream> outputStreamSupplier) {
this.lazyInitOutputStreamSupplier = Suppliers.memoize(outputStreamSupplier);
}
@Override
public void write(int b) throws IOException {
lazyInitOutputStreamSupplier.get().write(b);
}
@Override
public void write(byte b[]) throws IOException {
lazyInitOutputStreamSupplier.get().write(b);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
lazyInitOutputStreamSupplier.get().write(b,off,len);
}
public static LazyInitOutputStream lazyFileOutputStream(final File file) {
return lazyFileOutputStream(file,false);
}
public static LazyInitOutputStream lazyFileOutputStream(final File file,final boolean append) {
return new LazyInitOutputStream(new Supplier<OutputStream>() {
@Override
public OutputStream get() {
try {
return new FileOutputStream(file,append);
} catch (FileNotFoundException e) {
throw Throwables.propagate(e);
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但我看到有InputSupplier/OutputSupplier我可以使用的接口...除了他们不扩展供应商所以我不能使用这里需要的记忆功能,因为我不希望它OutputSupplier像一个工厂.
另外还有Filesapi:
public static OutputSupplier<FileOutputStream> newOutputStreamSupplier(File file,
boolean append)
Run Code Online (Sandbox Code Playgroud)
有没有办法可以使用OutputSupplier,它会比我现在的代码更优雅?
OutputSupplier没有实现供应商的原因吗?
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |