java nio笔记

本文详细介绍了Java NIO的主要组件,包括channels、selectors、buffers和file系统操作。讲解了Channel、ByteChannel、Selector、Buffer等重要接口的功能和使用场景,以及异步通道AsynchronousChannelGroup和文件操作FileChannel。此外,还概述了字符集、文件系统和网络编程的相关类。通过对这些核心概念的解析,帮助读者全面理解Java NIO的机制和应用。
摘要由CSDN通过智能技术生成

java nio主要包括java.nio.channels、java.nio.charset、java.nio.file三个包;
(java.nio.channels有各种channel、selector等,对应传统IO的input/output stream、reader/writer等;)
(java.nio.charset是字符集、编码和解码等;)
(java.nio.file是文件和目录功能,以及文件系统等;对应传统IO的File、FileSystem等;)

java.nio.channels的主要类或接口:
Channel、ByteChannel、ReadableByteChannel、WritableByteChannel、ScatteringByteChannel、SeekableByteChannel、GatheringByteChannel、NetworkChannel、MulticastChannel、InterruptibleChannel、FileChannel、AsynchronousSocketChannel、AsynchronousServerSocketChannel、AsynchronousByteChannel、AsynchronousChannel、AsynchronousFileChannel、AsynchronousChannelGroup、DatagramChannel、SelectableChannel、ServerSocketChannel、SocketChannel、Channels、Pipe、Selector、SelectionKey、MembershipKey、FileLock:

java.nio.channels.spi的几个类:
AbstractInterruptibleChannel、AbstractSelectableChannel、AbstractSelectionKey、AbstractSelector、AsynchronousChannelProvider、SelectorProvider

Channel接口继承Closeable接口,代表对文件、socket、硬件设备等的IO操作;
当Channel为close时进行操作,会抛出ClosedChannelException异常;(可以用isOpen方法来测试是否关闭)
任何Channel的实现类必须是线程安全的;

ReadableByteChannel接口继承Channel,是能够读取字节的channel;提供read方法,用于将channel中的字节序列读取到buffer;(当多个线程同时read时,只能有一个真正read,其它会阻塞;这里的buffer是java.nio.ByteBuffer类型;)

WritableByteChannel接口继承Channel,是能够写入字节的channel;提供write方法,用于将buffer中的字节序列写入到channel中;(当多个线程同时write时,只能有一个真正write,其它会阻塞;这里的buffer是java.nio.ByteBuffer类型;)

ByteChannel接口继承ReadableByteChannel和WritableByteChannel,代表既能读又能写;

AsynchronousChannel接口继承Channel,支持异步IO操作,通常和Future、CompletionHandler结合使用;

AsynchronousByteChannel接口继承AsynchronousChannel,提供read、write方法,是ByteChannel的异步版本;

SeekableByteChannel接口继承ByteChannel,维护一个当前位置;提供read、write、position、size、truncate方法,(可以调用java.nio.file.Files#newByteChannel得到实例;)

ScatteringByteChannel接口继承ReadableByteChannel,将channel中字节读取到buffer数组 (和GatheringByteChannel刚好相反);

GatheringByteChannel接口继承WritableByteChannel,将buffer数组中字节写入到channel (和ScatteringByteChannel刚好相反);

InterruptibleChannel接口继承Channel,可以被异步关闭或中断;

AbstractInterruptibleChannel抽象类实现Channel、InterruptibleChannel接口,主要方法有begin、end、close等,多个方法加了同步;

SelectableChannel抽象类继承AbstractInterruptibleChannel,是可以通过Selector多路复用的channel;
(主要方法有provider、isRegistered、register、isBlocking、configureBlocking等;)
(使用selector前必须先注册,用register方法返回SelectionKey实例;可以执行deregistered来取消注册;)
(既可以是blocking模式,也可以是non-blocking模式;刚创建的channel是blocking模式)

AbstractSelectableChannel抽象类继承SelectableChannel,封装了SelectorProvider provider、SelectionKey[] keys等字段;(对addKey、findKey、removeKey、haveValidKeys、isRegistered、register、configureBlocking等进行了实现;)

Selector抽象类实现Closeable接口,代表选择器;
(主要方法有open、isOpen、provider、keys、selectedKeys、selectNow、select、wakeup等;)
(其中open方法可以通过SelectorProvider创建一个Selector实例;)
(参见 http://ifeve.com/selectors/)

SelectionKey抽象类代表Selector和SelectableChannel的一次注册;
(主要方法有channel、selector、isValid、cancel、attach、isWritable、isAcceptable、isReadable等;)

AbstractSelector抽象类是Selector子类;
(主要方法有isOpen、cancelledKeys、close、provider、register、deregister、begin、end等;)

AbstractSelectionKey抽象类是SelectionKey子类;实现了cancel等方法;(其中的Selector使用AbstractSelector实例;)

SelectorProvider抽象类用于提供selector和selectable channel,是一个工具类;
(被多个类和方法用到,比如java.nio.channels.Pipe#open、java.nio.channels.DatagramChannel#open、java.nio.channels.Selector#open等;)
(主要方法有provider、openSelector、openSocketChannel、openServerSocketChannel、openPipe、openDatagramChannel等;)

AsynchronousChannelProvider抽象类提供异步channel,是一个工具类;

NetworkChannel接口继承Channel,代表网络中的socket;
(主要方法有bind、getLocalAddress、setOption、getOption、supportedOptions等;)

MulticastChannel接口继承NetworkChannel,支持IP多播;主要方法有join、close;

ServerSocketChannel抽象类继承AbstractSelectableChannel,并实现NetworkChannel接口;(主要方法有socket、accept、bind、open、getLocalAddress等;)

SocketChannel抽象类继承AbstractSelectableChannel,并实现NetworkChannel、ByteChannel、ScatteringByteChannel、GatheringByteChannel接口;(主要方法有getLocalAddress、getRemoteAddress、write、read、finishConnect、connect、isConnected、socket、open、bind等;)

DatagramChannel抽象类继承AbstractSelectableChannel,并实现MulticastChannel、ByteChannel、ScatteringByteChannel、GatheringByteChannel接口;(主要方法有open、socket、isConnected、connect、disconnect、getRemoteAddress、receive、send、read、write等;)

AsynchronousSocketChannel抽象类实现AsynchronousByteChannel、NetworkChannel接口;(主要方法有getLocalAddress、write、read、connect、getRemoteAddress、open、bind等;)

AsynchronousServerSocketChannel抽象类实现AsynchronousChannel、NetworkChannel接口;(主要方法有getLocalAddress、open、bind、accept等;)

FileChannel抽象类继承AbstractInterruptibleChannel,并实现SeekableByteChannel、GatheringByteChannel、ScatteringByteChannel接口;(主要方法有open、read、write、position、size、truncate、force、transferTo、transferFrom、lock、tryLock等;)

AsynchronousFileChannel抽象类实现AsynchronousChannel,用于对文件的异步读写操作,没有当前位置的说法;(主要方法有open、read、write、size、truncate、force、lock、tryLock等;)

AsynchronousChannelGroup抽象类是用于资源共享的异步channel集合;
(和传统线程池类似,也提供了withFixedThreadPool、withCachedThreadPool、withThreadPool等方法;)

Channels类是一个工具类,提供静态方法来支持传统IO和channel的相互转换;
(主要方法有newInputStream、newOutputStream、newChannel、newReader、newWriter等;)

Pipe抽象类封装了两个channel,代表无向的管道;
(内部类SourceChannel代表读取的channel,内部类SinkChannel代表写入的channel;)(主要方法有source、sink、open等;)

MembershipKey抽象类代表IP多播集合(与MulticastChannel相关),主要方法有drop、block、unblock、channel、group、sourceAddress等;

FileLock抽象类代表一个文件region的锁,可以通过FileChannel#lock、FileChannel#tryLock方法获取;(FileLock可以是exclusive或shared的;)(主要方法有release、overlaps、size、isShared、position、acquiredBy、channel等;)

java.nio.charset的主要类或接口:
Charset、CharsetDecoder、CharsetEncoder、CoderResult、CodingErrorAction、StandardCharsets、CharsetProvider:

Charset抽象类代表16位的Unicode,主要方法有contains、displayName、aliases、name、defaultCharset、availableCharsets、decode、encode等;(可以通过newDecoder、newEncoder获取CharsetDecoder和CharsetEncoder;)

CharsetEncoder抽象类根据特定charset,将16位Unicode字符编码为字节;

CharsetDecoder抽象类根据特定charset,将字节编码为16位Unicode字符;

CodingErrorAction类代表编码错误动作,被CharsetEncoder和CharsetDecoder使用;

CoderResult类代表编码结果,方法有isUnderflow、isOverflow、isError、isUnmappable等;

StandardCharsets类封装了多个Charset类型的变量,如UTF_8、UTF_16、ISO_8859_1等;

CharsetProvider抽象类提供Charset的服务,它是一种jdk spi;

java.nio.file的主要类或接口:
AccessMode、CopyMoveHelper、CopyOption、DirectoryStream、Files、FileStore、FileSystem、FileSystems、FileTreeIterator、FileTreeWalker、FileVisitOption、FileVisitor、FileVisitResult、LinkOption、LinkPermission、OpenOption、Path、PathMatcher、Paths、SecureDirectoryStream、SimpleFileVisitor、StandardCopyOption、StandardOpenOption、StandardWatchEventKinds、TempFileHelper、Watchable、WatchEvent、WatchKey、WatchService、FileSystemProvider、FileTypeDetector:

AccessMode是一个枚举,代表对文件的访问模式,有READ、WRITE、EXECUTE;

CopyMoveHelper类是文件移动、复制工具类;使用了StandardOpenOption和StandardCopyOption枚举、Files等类;

OpenOption接口用于配置如何打开或创建文件,被Files等多个类使用;

CopyOption接口用于配置如何复制或移动文件,被Files等多个类使用;

LinkOption枚举实现OpenOption、CopyOption接口,定义如何处理symbolic links;

StandardCopyOption枚举实现CopyOption接口,提供Replace、Copy、Move三种操作选项;

StandardOpenOption枚举实现OpenOption接口,提供read、write、append、truncate、create等多种操作选项;

FileVisitOption枚举定义了文件树遍历选项,只有一个FOLLOW_LINKS;

DirectoryStream接口代表目录流,可以通过Files.newDirectoryStream获得,主要方法是iterator;

SecureDirectoryStream接口继承DirectoryStream;主要方法有move、deleteDirectory、deleteFile、newByteChannel、newDirectoryStream;

Files类是一个工具类,提供多个静态方法对文件和目录进行操作;
(主要方法有newInputStream、newOutputStream、newByteChannel、newDirectoryStream、createFile、createDirectory、createDirectories、
createTempFile、createTempDirectory、createSymbolicLink、delete、deleteIfExists、copy、move、isDirectory、getLastModifiedTime、exists、isReadable、isWritable、walkFileTree、newBufferedReader、newBufferedWriter、readAllBytes、readAllLines、walk、list、find等;)

FileTreeWalker类对文件树进行遍历,主要方法是next、walk等;它被Files类的walkFileTree方法使用;

FileVisitor接口是文件的访问器,被Files类的walkFileTree方法作为参数使用;
(主要方法有preVisitDirectory、visitFile、visitFileFailed、postVisitDirectory;返回结果都是FileVisitResult类型;)(FileVisitor和FileTreeWalker区别是,前者更细粒度;)

SimpleFileVisitor简单实现了FileVisitor接口,各个方法仍需要重写;

FileVisitResult是枚举,代表FileVisitor的结果,有Continue、Terminate、SKIP_SUBTREE、SKIP_SIBLINGS四种;

TempFileHelper类用于创建临时文件和目录,主要方法有createTempFile、createTempDirectory;它被Files类的createTempFile等方法使用;

FileSystem抽象类代表文件系统,可通过FileSystems#getDefault获得实例;
(主要方法有isOpen、isReadOnly、getFileStores、getRootDirectories、getSeparator、getPath、getPathMatcher、newWatchService等;)

FileSystems类是工具类,依赖FileSystemProvider提供具体实现;
(主要方法有getDefault、getFileSystem、newFileSystem等;可返回FileSystem实例;)

FileStore抽象类代表文件存储;可通过Files#getFileStore、FileSystem#getFileStores获取实例;(主要方法有name、type、isReadOnly、getTotalSpace、getUsableSpace、getAttribute等;)

PathMatcher接口用于匹配路径;提供matches方法;可通过FileSystem#getPathMatcher获取实例;

WatchService接口用于监控目录;可通过FileSystem#newWatchService创建实例;(主要方法有take、poll、close;)

Watchable接口代表可以被watch的对象;通过register方法向WatchService注册来获取WatchKey;

WatchKey接口代表Watchable向WatchService注册的实例;
(主要方法有watchable、cancel、reset、pollEvents等;可通过WatchService#poll和take方法返回实例;)

WatchEvent接口代表观察到的event或repeated event;(在Watchable#register注册时被提供给WatchService;)(定义了静态内部接口Kind和Modifier,分别代表event的类型和修饰符;)(WatchEvent对外方法是kind、count、context;)

FileSystemProvider抽象类为文件系统提供服务,是一个jdk spi;
(主要方法有installedProviders、newFileSystem、getFileSystem、newInputStream、newOutputStream、newFileChannel、newByteChannel、newDirectoryStream、createDirectory、createSymbolicLink、delete、deleteIfExists、copy、move、getFileStore等;)(它为FileSystems和Files提供具体实现;)

FileTypeDetector抽象类是文件类型探测器,Files#probeContentType使用;主要方法有probeContentType;

FileTreeIterator是文件树迭代器,实现Iterator接口,封装了FileTreeWalker walker字段;被Files#walk、find方法使用;(主要方法有hasNext、next、close;)

Path接口继承Watchable、Iterable、Comparable接口,用于定位文件在文件系统的位置;(主要方法有getFileSystem、isAbsolute、getRoot、getFileName、getParent、startsWith、endsWith、toFile、register等;)

Paths是工具类,用于将URI变为Path;主要方法是get;

LinkPermission类继承BasicPermission,代表link创建操作的权限;包括hard和symbolic两种链接;

StandardWatchEventKinds类定义了标准事件类型;

java.nio.file.attribute的类或接口:
AclEntry、AclEntryFlag、AclEntryPermission、AclEntryType、AclFileAttributeView、AttributeView、BasicFileAttributes、BasicFileAttributeView、DosFileAttributes、DosFileAttributeView、FileAttribute、FileAttributeView、FileOwnerAttributeView、FileStoreAttributeView、FileTime、GroupPrincipal、PosixFileAttributes、PosixFileAttributeView、PosixFilePermission、PosixFilePermissions、UserDefinedFileAttributeView、UserPrincipal、UserPrincipalLookupService:

FileAttribute接口代表文件或目录属性;方法有name、value;

AttributeView接口代表属性视角,方法有name;

FileStoreAttributeView接口继承AttributeView,代表FileStore的属性视角;

FileAttributeView接口继承AttributeView,代表文件属性视角;(可通过Files#getFileAttributeView获取实例;)

UserDefinedFileAttributeView接口继承FileAttributeView,代表用户自定义文件属性视角;

BasicFileAttributeView接口继承FileAttributeView,代表基本文件属性视角;(被Files#setLastModifiedTime使用;)

DosFileAttributeView接口继承BasicFileAttributeView,代表Dos文件属性视角;

FileOwnerAttributeView接口可以读取或修改文件owner;方法有getOwner、setOwner;

PosixFileAttributeView接口继承BasicFileAttributeView、FileOwnerAttributeView;被Files#setPosixFilePermissions方法使用;

AclFileAttributeView接口继承FileOwnerAttributeView,用于读取、修改文件ACL或owner;(主要方法有getAcl、setAcl;)

AclEntryType枚举定义了acl entry的类型,有ALLOW、DENY、AUDIT、ALARM四种;

AclEntryPermission枚举定义了acl entry的权限,有read、write、append、execute、delete等多种;

AclEntryFlag枚举acl entry的flag,有FILE_INHERIT、DIRECTORY_INHERIT、NO_PROPAGATE_INHERIT、INHERIT_ONLY四种;

AclEntry类acl中的一个entry,封装了AclEntryType type、UserPrincipal who、Set< AclEntryPermission> perms、Set< AclEntryFlag> flags字段;(主要方法有build、setType、setPrincipal、setPermissions、setFlags等;)

BasicFileAttributes接口代表基本的文件或目录属性;(可通过Files.readAttributes获取实例;)(主要方法有lastModifiedTime、creationTime、isDirectory、isSymbolicLink、size等;)

DosFileAttributes接口继承BasicFileAttributes,代表Dos的文件属性;
(主要方法有isHidden、isReadOnly、isSystem、isArchive;)

PosixFileAttributes接口继承BasicFileAttributes,代表POSIX的文件属性;
(主要方法有owner、group、permissions;)

PosixFilePermission枚举代表Posix文件的权限,有read、write、execute等多种;(可通过PosixFileAttributes#permissions获取实例;)

PosixFilePermissions是为PosixFilePermission服务的静态工具类,方法有asFileAttribute等;

UserPrincipal接口继承java.security.Principal,代表用户对文件的访问权限;(可通过PosixFileAttributes#owner获取实例;)

GroupPrincipal接口继承UserPrincipal,代表用户组对文件的访问权限;(可通过PosixFileAttributes#group获取实例;)

UserPrincipalLookupService抽象类用于查看用户和组的权限;方法有lookupPrincipalByName、lookupPrincipalByGroupName;

FileTime类代表文件的时间戳属性;(可通过BasicFileAttributes#lastModifiedTime等多种方式获取实例;并被Files类使用)(主要方法有toInstant、toMillis、from、to、fromMillis、compareTo等;)

java.nio下面还有一些类如下:Bits、Buffer、ByteBuffer、ByteOrder、CharBuffer、CharBufferSpliterator、DirectByteBuffer、DoubleBuffer、FloatBuffer、HeapByteBuffer、HeapCharBuffer、HeapDoubleBuffer、HeapFloatBuffer、HeapIntBuffer、HeapLongBuffer、HeapShortBuffer、IntBuffer、LongBuffer、
MappedByteBuffer、ShortBuffer、StringCharBuffer等:

Bits是一个包私有的工具类,提供多个静态方法如swap、getChar、putChar、makeInt、makeLong、getFloat、putFloat、copyToArray等;

Buffer抽象类是一个基本类型数据的容器;
(主要方法有capacity、position、limit、reset、clear、isReadOnly、array、isDirect等;)

ByteBuffer抽象类继承Buffer,维护了byte[] hb字段;
(主要方法有allocate、allocateDirect、wrap等;)

ByteOrder类考虑字节顺序,分为大端big-endian和小端little-endian两种;
https://blog.csdn.net/dosthing/article/details/80641173 !!!

CharBuffer抽象类继承Buffer,维护char[] hb字段;
(主要方法有allocate、read、wrap、duplicate、get、put等;)

StringCharBuffer是CharBuffer子类,是包私有的;

CharBufferSpliterator类用于分割CharBuffer中的元素;主要方法有trySplit、forEachRemaining、tryAdvance等;

MappedByteBuffer抽象类继承ByteBuffer,代表文件的内存映射区域;
(主要方法有force、load、isLoaded等;调用了一些native方法如isLoaded0、load0、force0;)

DirectByteBuffer类继承MappedByteBuffer,代表堆外内存(和HeapByteBuffer相对应);
(大量利用unsafe的native方法,如unsafe.allocateMemory实现直接内存分配;)
https://www.jianshu.com/p/007052ee3773)

HeapByteBuffer类继承ByteBuffer,代表堆内存(和DirectByteBuffer相对应);
https://blog.csdn.net/xieyuooo/article/details/7547435

DoubleBuffer抽象类继承Buffer,维护double[] hb字段;
(主要方法有allocate、wrap、duplicate、get、put等;)

FloatBuffer抽象类继承Buffer,维护float[] hb字段;
(主要方法有allocate、wrap、duplicate、get、put等;)

LongBuffer抽象类继承Buffer,维护long[] hb字段;
(主要方法有allocate、wrap、duplicate、get、put等;)

IntBuffer抽象类继承Buffer,维护int[] hb字段;
(主要方法有allocate、wrap、duplicate、get、put等;)

ShortBuffer抽象类继承Buffer,维护short[] hb字段;
(主要方法有allocate、wrap、duplicate、get、put等;)

HeapShortBuffer是ShortBuffer子类;其他都以此类推;
(注意HeapShortBuffer代表读写,而HeapShortBufferR代表只读;)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值