我正在分析FileOutputStream
。
getChannel()
方法可以返回null
吗?如果是这样,在什么情况下?
答案 0 :(得分:3)
FileOutputStream
getChannel()
方法代码
public FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, false, true, this, append);
/*
* Increment fd's use count. Invoking the channel's close()
* method will result in decrementing the use count set for
* the channel.
*/
fd.incrementAndGetUseCount();
}
return channel;
}
}
调用FileChannelImpl.open()
,此代码始终创建一个新对象
public static FileChannel open(FileDescriptor fd,
boolean readable, boolean writable,
Object parent, boolean append)
{
return new FileChannelImpl(fd, readable, writable, parent, append);
}
答案 1 :(得分:2)
public FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, false, true, append, this);
fd.incrementAndGetUseCount();
}
return channel;
}
}
显示无法返回null
。
答案 2 :(得分:2)
查看来源 FileChannelImpl#open
方法Open()
return new FileChannelImpl(...)
所以它创建了新的引用,它不能是null
答案 3 :(得分:1)
来自Java Source:
/**
* Returns the unique {@link java.nio.channels.FileChannel FileChannel}
* object associated with this file output stream. </p>
*
* <p> The initial {@link java.nio.channels.FileChannel#position()
* </code>position<code>} of the returned channel will be equal to the
* number of bytes written to the file so far unless this stream is in
* append mode, in which case it will be equal to the size of the file.
* Writing bytes to this stream will increment the channel's position
* accordingly. Changing the channel's position, either explicitly or by
* writing, will change this stream's file position.
*
* @return the file channel associated with this file output stream
*
* @since 1.4
* @spec JSR-51
*/
public FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, false, true, append, this);
/*
* Increment fd's use count. Invoking the channel's close()
* method will result in decrementing the use count set for
* the channel.
*/
fd.incrementAndGetUseCount();
}
return channel;
}
}
因此无法返回null
。