2

我正在分析FileOutputStream.

方法可以getChannel()返回null吗?如果有,在什么情况下?

4

4 回答 4

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);
 }
于 2012-11-12T09:12:30.193 回答
2
public FileChannel getChannel() {
    synchronized (this) {
        if (channel == null) {
            channel = FileChannelImpl.open(fd, false, true, append, this);
            fd.incrementAndGetUseCount();
        }
        return channel;
    }
}

显示null无法退货。

于 2012-11-12T09:09:33.177 回答
2

看下FileChannelImpl#open的源码

方法Open()
return new FileChannelImpl(...)
,所以它创建新的参考,它不能null

于 2012-11-12T09:13:48.690 回答
1

来自 Java 源代码:

    /**
 * 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

于 2012-11-12T09:12:16.180 回答