文档章节

java.nio.channels.FileChannel源码解读

A__17
 A__17
发布于 2017/08/21 23:06
字数 2524
阅读 2
收藏 0
点赞 0
评论 0

版本:JDK7

package java.nio.channels;

import java.io.; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.spi.AbstractInterruptibleChannel; import java.nio.file.; import java.nio.file.attribute.FileAttribute; import java.nio.file.spi.*; import java.util.Set; import java.util.HashSet; import java.util.Collections;

public abstract class FileChannel extends AbstractInterruptibleChannel implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel {

protected FileChannel() { }

/**
 * Opens or creates a file, returning a file channel to access the file.
 *
 * <p> The {[@code](https://my.oschina.net/codeo) options} parameter determines how the file is opened.
 * The {[@link](https://my.oschina.net/u/393) StandardOpenOption#READ READ} and {[@link](https://my.oschina.net/u/393) StandardOpenOption#WRITE
 * WRITE} options determine if the file should be opened for reading and/or
 * writing. If neither option (or the {[@link](https://my.oschina.net/u/393) StandardOpenOption#APPEND APPEND}
 * option) is contained in the array then the file is opened for reading.
 * By default reading or writing commences at the beginning of the file.
 * [@since](https://my.oschina.net/u/266547)   1.7
 */
public static FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    FileSystemProvider provider = path.getFileSystem().provider();
    return provider.newFileChannel(path, options, attrs);
}

private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];

/**
 * Opens or creates a file, returning a file channel to access the file.
 * @since   1.7
 */
public static FileChannel open(Path path, OpenOption... options) throws IOException {
    Set<OpenOption> set = new HashSet<OpenOption>(options.length);
    Collections.addAll(set, options);
    return open(path, set, NO_ATTRIBUTES);
}

// -- Channel operations --

/**
 * Reads a sequence of bytes from this channel into the given buffer.
 */
public abstract int read(ByteBuffer dst) throws IOException;

/**
 * Reads a sequence of bytes from this channel into a subsequence of the
 * given buffers.
 */
public abstract long read(ByteBuffer[] dsts, int offset, int length)
    throws IOException;

/**
 * Reads a sequence of bytes from this channel into the given buffers.
 */
public final long read(ByteBuffer[] dsts) throws IOException {
    return read(dsts, 0, dsts.length);
}

/**
 * Writes a sequence of bytes to this channel from the given buffer.
 */
public abstract int write(ByteBuffer src) throws IOException;

/**
 * Writes a sequence of bytes to this channel from a subsequence of the given buffers.
 */
public abstract long write(ByteBuffer[] srcs, int offset, int length)
    throws IOException;

/**
 * Writes a sequence of bytes to this channel from the given buffers.
 */
public final long write(ByteBuffer[] srcs) throws IOException {
    return write(srcs, 0, srcs.length);
}

/**
 * Returns this channel's file position.
 */
public abstract long position() throws IOException;

/**
 * Sets this channel's file position.
 *
 * <p> Setting the position to a value that is greater than the file's
 * current size is legal but does not change the size of the file.  A later
 * attempt to read bytes at such a position will immediately return an
 * end-of-file indication.  A later attempt to write bytes at such a
 * position will cause the file to be grown to accommodate the new bytes;
 * the values of any bytes between the previous end-of-file and the
 * newly-written bytes are unspecified.  </p>
 *
 * 如果将位置设置在文件结束符之后,然后试图从文件通道中读取数据,读方法将返回-1 —— 文件结束标志。
 * 如果将位置设置在文件结束符之后,然后向通道中写数据,文件将撑大到当前位置并(从当前位置开始)写入数据。这可能导致“文件空洞”,磁盘上物理文件中写入的数据间有空隙。
 *
 * @param  newPosition
 *         The new position, a non-negative integer counting
 *         the number of bytes from the beginning of the file

 */
public abstract FileChannel position(long newPosition) throws IOException;

/**
 * Returns the current size of this channel's file. 
 */
public abstract long size() throws IOException;

/**
 * Truncates this channel's file to the given size. 截取一个文件
 * 
 * <p> If the given size is less than the file's current size then the file
 * is truncated, discarding any bytes beyond the new end of the file.  If
 * the given size is greater than or equal to the file's current size then
 * the file is not modified.  In either case, if this channel's file
 * position is greater than the given size then it is set to that size.
 */
public abstract FileChannel truncate(long size) throws IOException;

/**
 * Forces any updates to this channel's file to be written to the storage
 * device that contains it.

 * 将通道里尚未写入磁盘的数据强制写到磁盘上。
 * 说明:
 *		1)操作系统将数据缓存在内存中,所以无法保证写入到FileChannel里的数据一定会即时写到磁盘上。
 * 		2)如果要保证写入到FileChannel里的数据即时写到磁盘上,需要调用force()方法,参数表示是否将文件的元数据写到磁盘上。
 */
public abstract void force(boolean metaData) throws IOException;

// 通道之间的数据传输
/**
 * Transfers bytes from this channel's file to the given writable byte channel.
 */
public abstract long transferTo(long position, long count, WritableByteChannel target) throws IOException;

/**
 * Transfers bytes into this channel's file from the given readable byte channel.
 */
public abstract long transferFrom(ReadableByteChannel src, long position, long count) throws IOException;

/**
 * Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.
 *
 * This method does not modify this channel's position.  
 * If the given position is greater than the file's current size then no bytes are read.
 */
public abstract int read(ByteBuffer dst, long position) throws IOException;

/**
 * Writes a sequence of bytes to this channel from the given buffer, starting at the given file position.
 *
 * This method does not modify this channel's position.  
 * If the given position is greater than the file's current size then the file will be grown to accommodate the new bytes;
 * the values of any bytes between the previous end-of-file and the newly-written bytes are unspecified.
 */
public abstract int write(ByteBuffer src, long position) throws IOException;


// -- Memory-mapped buffers --

/**
 * A typesafe enumeration for file-mapping modes.
 *
 * @since 1.4
 *
 * @see java.nio.channels.FileChannel#map
 */
public static class MapMode {

    /**
     * Mode for a read-only mapping.
     */
    public static final MapMode READ_ONLY = new MapMode("READ_ONLY");

    /**
     * Mode for a read/write mapping.
     */
    public static final MapMode READ_WRITE = new MapMode("READ_WRITE");

    /**
     * Mode for a private (copy-on-write) mapping.
     */
    public static final MapMode PRIVATE = new MapMode("PRIVATE");

    private final String name;

    private MapMode(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }

}

/**
 * Maps a region of this channel's file directly into memory.
 *
 *  A region of a file may be mapped into memory in one of three modes:
 *
 * Read-only、Read/write、Private
 *
 * @param  mode
 *         One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link
 *         MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE
 *         PRIVATE} defined in the {@link MapMode} class, according to
 *         whether the file is to be mapped read-only, read/write, or
 *         privately (copy-on-write), respectively
 *
 * @param  position
 *         The position within the file at which the mapped region
 *         is to start; must be non-negative
 *
 * @param  size
 *         The size of the region to be mapped; must be non-negative and
 *         no greater than {@link java.lang.Integer#MAX_VALUE}
 *
 *
 * @see java.nio.channels.FileChannel.MapMode
 * @see java.nio.MappedByteBuffer
 */
public abstract MappedByteBuffer map(MapMode mode, long position, long size) throws IOException;


// -- Locks --

/**
 * Acquires a lock on the given region of this channel's file.
 *
 * <p> An invocation of this method will block until the region can be
 * locked, this channel is closed, or the invoking thread is interrupted,
 * whichever comes first.
 *
 * <p> If this channel is closed by another thread during an invocation of
 * this method then an {@link AsynchronousCloseException} will be thrown.
 *
 * <p> If the invoking thread is interrupted while waiting to acquire the
 * lock then its interrupt status will be set and a {@link
 * FileLockInterruptionException} will be thrown.  If the invoker's
 * interrupt status is set when this method is invoked then that exception
 * will be thrown immediately; the thread's interrupt status will not be
 * changed.
 *
 * <p> The region specified by the <tt>position</tt> and <tt>size</tt>
 * parameters need not be contained within, or even overlap, the actual
 * underlying file.  Lock regions are fixed in size; if a locked region
 * initially contains the end of the file and the file grows beyond the
 * region then the new portion of the file will not be covered by the lock.
 * If a file is expected to grow in size and a lock on the entire file is
 * required then a region starting at zero, and no smaller than the
 * expected maximum size of the file, should be locked.  The zero-argument
 * {@link #lock()} method simply locks a region of size {@link
 * Long#MAX_VALUE}.
 *
 * <p> Some operating systems do not support shared locks, in which case a
 * request for a shared lock is automatically converted into a request for
 * an exclusive lock.  Whether the newly-acquired lock is shared or
 * exclusive may be tested by invoking the resulting lock object's {@link
 * FileLock#isShared() isShared} method.
 *
 * <p> File locks are held on behalf of the entire Java virtual machine.
 * They are not suitable for controlling access to a file by multiple
 * threads within the same virtual machine.  </p>
 *
 * @param  position
 *         The position at which the locked region is to start; must be
 *         non-negative
 *
 * @param  size
 *         The size of the locked region; must be non-negative, and the sum
 *         <tt>position</tt> + <tt>size</tt> must be non-negative
 *
 * @param  shared
 *         <tt>true</tt> to request a shared lock, in which case this
 *         channel must be open for reading (and possibly writing);
 *         <tt>false</tt> to request an exclusive lock, in which case this
 *         channel must be open for writing (and possibly reading)
 *
 * @return  A lock object representing the newly-acquired lock
 *
 * @throws  IllegalArgumentException
 *          If the preconditions on the parameters do not hold
 *
 * @throws  ClosedChannelException
 *          If this channel is closed
 *
 * @throws  AsynchronousCloseException
 *          If another thread closes this channel while the invoking
 *          thread is blocked in this method
 *
 * @throws  FileLockInterruptionException
 *          If the invoking thread is interrupted while blocked in this
 *          method
 *
 * @throws  OverlappingFileLockException
 *          If a lock that overlaps the requested region is already held by
 *          this Java virtual machine, or if another thread is already
 *          blocked in this method and is attempting to lock an overlapping
 *          region
 *
 * @throws  NonReadableChannelException
 *          If <tt>shared</tt> is <tt>true</tt> this channel was not
 *          opened for reading
 *
 * @throws  NonWritableChannelException
 *          If <tt>shared</tt> is <tt>false</tt> but this channel was not
 *          opened for writing
 *
 * @throws  IOException
 *          If some other I/O error occurs
 *
 * @see     #lock()
 * @see     #tryLock()
 * @see     #tryLock(long,long,boolean)
 */
public abstract FileLock lock(long position, long size, boolean shared) throws IOException;

/**
 * Acquires an exclusive lock on this channel's file.
 *
 * <p> An invocation of this method of the form <tt>fc.lock()</tt> behaves
 * in exactly the same way as the invocation
 *
 * <pre>
 *     fc.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false) </pre>
 *
 * @return  A lock object representing the newly-acquired lock
 *
 * @throws  ClosedChannelException
 *          If this channel is closed
 *
 * @throws  AsynchronousCloseException
 *          If another thread closes this channel while the invoking
 *          thread is blocked in this method
 *
 * @throws  FileLockInterruptionException
 *          If the invoking thread is interrupted while blocked in this
 *          method
 *
 * @throws  OverlappingFileLockException
 *          If a lock that overlaps the requested region is already held by
 *          this Java virtual machine, or if another thread is already
 *          blocked in this method and is attempting to lock an overlapping
 *          region of the same file
 *
 * @throws  NonWritableChannelException
 *          If this channel was not opened for writing
 *
 * @throws  IOException
 *          If some other I/O error occurs
 *
 * @see     #lock(long,long,boolean)
 * @see     #tryLock()
 * @see     #tryLock(long,long,boolean)
 */
public final FileLock lock() throws IOException {
    return lock(0L, Long.MAX_VALUE, false);
}

/**
 * Attempts to acquire a lock on the given region of this channel's file.
 *
 * <p> This method does not block.  An invocation always returns
 * immediately, either having acquired a lock on the requested region or
 * having failed to do so.  If it fails to acquire a lock because an
 * overlapping lock is held by another program then it returns
 * <tt>null</tt>.  If it fails to acquire a lock for any other reason then
 * an appropriate exception is thrown.
 *
 * <p> The region specified by the <tt>position</tt> and <tt>size</tt>
 * parameters need not be contained within, or even overlap, the actual
 * underlying file.  Lock regions are fixed in size; if a locked region
 * initially contains the end of the file and the file grows beyond the
 * region then the new portion of the file will not be covered by the lock.
 * If a file is expected to grow in size and a lock on the entire file is
 * required then a region starting at zero, and no smaller than the
 * expected maximum size of the file, should be locked.  The zero-argument
 * {@link #tryLock()} method simply locks a region of size {@link
 * Long#MAX_VALUE}.
 *
 * <p> Some operating systems do not support shared locks, in which case a
 * request for a shared lock is automatically converted into a request for
 * an exclusive lock.  Whether the newly-acquired lock is shared or
 * exclusive may be tested by invoking the resulting lock object's {@link
 * FileLock#isShared() isShared} method.
 *
 * <p> File locks are held on behalf of the entire Java virtual machine.
 * They are not suitable for controlling access to a file by multiple
 * threads within the same virtual machine.  </p>
 *
 * @param  position
 *         The position at which the locked region is to start; must be
 *         non-negative
 *
 * @param  size
 *         The size of the locked region; must be non-negative, and the sum
 *         <tt>position</tt> + <tt>size</tt> must be non-negative
 *
 * @param  shared
 *         <tt>true</tt> to request a shared lock,
 *         <tt>false</tt> to request an exclusive lock
 *
 * @return  A lock object representing the newly-acquired lock,
 *          or <tt>null</tt> if the lock could not be acquired
 *          because another program holds an overlapping lock
 *
 * @throws  IllegalArgumentException
 *          If the preconditions on the parameters do not hold
 *
 * @throws  ClosedChannelException
 *          If this channel is closed
 *
 * @throws  OverlappingFileLockException
 *          If a lock that overlaps the requested region is already held by
 *          this Java virtual machine, or if another thread is already
 *          blocked in this method and is attempting to lock an overlapping
 *          region of the same file
 *
 * @throws  IOException
 *          If some other I/O error occurs
 *
 * @see     #lock()
 * @see     #lock(long,long,boolean)
 * @see     #tryLock()
 */
public abstract FileLock tryLock(long position, long size, boolean shared)
    throws IOException;

/**
 * Attempts to acquire an exclusive lock on this channel's file.
 *
 * <p> An invocation of this method of the form <tt>fc.tryLock()</tt>
 * behaves in exactly the same way as the invocation
 *
 * <pre>
 *     fc.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre>
 *
 * @return  A lock object representing the newly-acquired lock,
 *          or <tt>null</tt> if the lock could not be acquired
 *          because another program holds an overlapping lock
 *
 * @throws  ClosedChannelException
 *          If this channel is closed
 *
 * @throws  OverlappingFileLockException
 *          If a lock that overlaps the requested region is already held by
 *          this Java virtual machine, or if another thread is already
 *          blocked in this method and is attempting to lock an overlapping
 *          region
 *
 * @throws  IOException
 *          If some other I/O error occurs
 *
 * @see     #lock()
 * @see     #lock(long,long,boolean)
 * @see     #tryLock(long,long,boolean)
 */
public final FileLock tryLock() throws IOException {
    return tryLock(0L, Long.MAX_VALUE, false);
}

}这里输入代码

© 著作权归作者所有

共有 人打赏支持
A__17
粉丝 2
博文 91
码字总数 102581
作品 0
朝阳
可使用 FileChannel 来写入任何 InputStream 吗?

我能够将任何 InputStream 写入到 FileChannel 吗? 我先用 java.nio.channels.FileChannel 打开文件并锁定,然后我想通过 InputStream 获取到的数据写入到文件中,InputStream 可能是另外一...

绿悠悠 ⋅ 2011/07/08 ⋅ 1

java nio 文件传输

import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class LargeMappedFiles { static int length = 0x8FFFFFF; // 128 Mb......

idoz ⋅ 2012/02/28 ⋅ 0

Android6.0源码解读之Activity点击事件分发机制

本篇博文是Android点击事件分发机制系列博文的第四篇,主要是从解读Activity类的源码入手,根据源码理清Activity点击事件分发原理,并掌握Activity点击事件分法机制。特别声明的是,本源码解...

mynameishuangshuai ⋅ 2016/10/23 ⋅ 0

Android6.0源码解读之View点击事件分发机制

本篇博文是Android点击事件分发机制系列博文的第二篇,主要是从解读View类的源码入手,根据源码理清View点击事件分发原理,并掌握View点击事件分法机制。特别声明的是,本源码解读是基于最新...

mynameishuangshuai ⋅ 2016/10/23 ⋅ 0

升级到JDK9的一个BUG,你了解吗

概述 前几天在一个群里看到一个朋友发了一个demo,说是JDK的bug,昨天在JVM的一个群里又有朋友发了,觉得挺有意思,分享给大家,希望大家升级JDK的版本的时候注意下是否存在这样的代码,如果...

你假笨 ⋅ 06/06 ⋅ 0

Android6.0触摸事件分发机制解读

本篇博文是Android触摸事件分发机制系列博文的第一篇,带领大家从全局掌握Android触摸事件分发机制。特别声明的是,本源码解读是基于最新的Android6.0版本。 (一)Android6.0源码解读之Vie...

mynameishuangshuai ⋅ 2016/10/24 ⋅ 0

JAVA之道丨文件复制的四种方法

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.i......

启示录是真的 ⋅ 05/26 ⋅ 0

关于Birt source的讨论和疑问

最近遇到一个头疼的问题,客户需求使用Myriad-Italic字体显示某些栏位,在模板中设出来以后,并不能正确显示,而是显示成Myriad,也就是说没有斜体。 为什么不能显示成Myriad-Italic呢?这个...

aine_pan ⋅ 2012/09/24 ⋅ 0

Mina系列文章索引

写了很多关于Apache Mina的文章,为了方便大家阅读,我将关于mina的一些文章做点儿索引。 Mina官网资料----------------------------------------------------------------- Mina官网是学习m...

Gaischen ⋅ 2012/11/28 ⋅ 15

Android6.0源码解读之ViewGroup点击事件分发机制

本篇博文是Android点击事件分发机制系列博文的第三篇,主要是从解读ViewGroup类的源码入手,根据源码理清ViewGroup点击事件分发原理,明白ViewGroup和View点击事件分发的关系,并掌握ViewGro...

mynameishuangshuai ⋅ 2016/10/24 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

Cube、Cuboid 和 Cube Segment

1.Cube (或Data Cube),即数据立方体,是一种常用于数据分析与索引的技术;它可以对原始数据建立多维度索引。通过 Cube 对数据进行分析,可以大大加快数据的查询效率 2.Cuboid 在 Kylin 中特...

无精疯 ⋅ 21分钟前 ⋅ 0

github太慢

1:用浏览器访问 IPAddress.com or http://tool.chinaz.com 使用 IP Lookup 工具获得github.com和github.global.ssl.fastly.net域名的ip地址 2:/etc/hosts文件中添加如下格式(IP最好自己查一...

whoisliang ⋅ 22分钟前 ⋅ 0

非阻塞同步之 CAS

为解决线程安全问题,互斥同步相当于以时间换空间。多线程情况下,只有一个线程可以访问同步代码。这种同步也叫阻塞同步(Blocking Synchronization). 这种同步属于一种悲观并发策略。认为只...

长安一梦 ⋅ 33分钟前 ⋅ 0

云计算的选择悖论如何对待?

人们都希望在工作和生活中有所选择。但心理学家的调查研究表明,在多种选项中进行选择并不一定会使人们更快乐,甚至不会产生更好的决策。心理学家Barry Schwartz称之为“选择悖论”。云计算为...

linux-tao ⋅ 35分钟前 ⋅ 0

我的第一篇个人博客

虽然这是个技术博客,但是,我总是想写一些自己的东西,所有就大胆的在这里写下了第一篇非技术博客。技术博客也很久没有更新,个人原因。 以后自己打算在这里写一些非技术博客,可能个人观点...

Mrs_CoCo ⋅ 36分钟前 ⋅ 0

Redis 注册为 Windows 服务

Redis 注册为 Windows 服务 redis 注册为 windows 服务相关命令 注册服务 redis-server.exe –service-install redis.windows.conf 删除服务 redis-server –service-uninstall 启动服务 re......

Os_yxguang ⋅ 36分钟前 ⋅ 0

世界那么大,语言那么多,为什么选择Micropython,它的优势在哪?

最近国内MicroPython风靡程序界,是什么原因导致它这么火呢?是因为他功能强大,遵循Mit协议开源么? 错!因为使用它真的是太舒服了!!! Micropython的由来,这得益于Damien George这位伟大...

bodasisiter ⋅ 40分钟前 ⋅ 0

docker 清理总结

杀死所有正在运行的容器 docker kill $(docker ps -a -q) 删除所有已经停止的容器(docker rm没有加-f参数,运行中的容器不会删掉) docker rm $(docker ps -a -q) 删除所有未打 dangling 标...

vvx1024 ⋅ 50分钟前 ⋅ 0

关于学习

以前学车的时候,教练说了这样的一句话:如果一个人坐在车上一直学,一直学,反而不如大家轮流着学。因为一个人一直学,就没有给自己留空间来反思和改进。而轮流着学的时候大家下来之后思考上...

mskk ⋅ 54分钟前 ⋅ 0

压缩工具之gzip-bzip2-xz

win下常见压缩工具:rar zip 7z linux下常见压缩工具:zip gz bz2 xz tar.gz tar.bz2 tar.xz gzip 不支持目录压缩 gzip 1.txt #压缩。执行后1.txt消失,生成1.txt.gz压缩文件 gzip -d 1.txt....

ZHENG-JY ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部