2

の API を分析しています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 に答える