输出流根据定义总是写入内容,所以我无法使用它。 在我们的项目中(我们有一个与 TRUNCATE_EXISTING 缺失相关的错误),未指定 WRITE 选项,但文件还是被(覆盖)写入了。 需要明确的是,以下两者有什么区别:
// OpenOption.CREATE, OpenOption.TRUNCATE_EXISTING, OpenOption.WRITE
Files.newOutputStream(file);
和
Files.newOutputStream(file, OpenOption.CREATE, OpenOption.TRUNCATE_EXISTING);
FileSystemProvider.newStreamOutput()
,它使用
newByteChannel()
来创建OutputStream,如源代码
中所示:
public OutputStream newOutputStream(Path path, OpenOption... options)
throws IOException
{
int len = options.length;
Set<OpenOption> opts ;
if (len == 0) {
opts = DEFAULT_OPEN_OPTIONS;
} else {
opts = new HashSet<>();
for (OpenOption opt: options) {
if (opt == StandardOpenOption.READ)
throw new IllegalArgumentException("READ not allowed");
opts.add(opt);
}
opts.add(StandardOpenOption.WRITE);
}
WritableByteChannel wbc = newByteChannel(path, opts);
if (wbc instanceof FileChannelImpl) {
((FileChannelImpl) wbc).setUninterruptible();
}
return Channels.newOutputStream(wbc);
}
此方法始终将 WRITE 添加到选项中。请注意,在未给出选项时使用的 DEFAULT_OPEN_OPTIONS 也包含 WRITE。newByteChannel()
WRITE
(或
APPEND
)来创建可写通道。
结论:使用或不使用 WRITE 没有(功能)差异。