当前位置:网站首页>01-nio basic ByteBuffer and filechannel
01-nio basic ByteBuffer and filechannel
2022-04-23 14:13:00 【All the names I thought of were used】
One 、channel and buffer
channel It is the channel of user communication ,buffer It's the buffer , Again from channel Before reading data , We need to read the data to buffer in , Again from buffer To remove . Again to channel Before writing data , Also write data to buffer in ,channel Again from buffer Take the data from .
common channel
- FileChannel
- SocketChannel
- ServerSocketChannel
Buffer There are many kinds of , The most common is ByteBuffer 了
Two 、ByteBuffer
ByteBuffer There are two patterns : Read mode and write mode
Write mode


Reading mode


Write mode ----> Reading mode : flip()
Reading mode ----> Write mode :clear()、compact()
( One ) compact and clear The difference between
clear

compact

( Two ) ByteBuffer Common methods
Reading method :
- get(): Every read position Will move forward by one
- get(int i): Read the first i Bytes ,position Can't move
Write method :
- write(Byte b)、write(Byte[])、write(ByteBuffer)
Allocate space
- allocate()
Reset position
- rewind: Reset position by 0 And clearly mask
- mask and reset
mask Used to mark the position ,reset Will position Set as mask The location of - position(int newPosition): Set new location
Use... Correctly buffer Example
public static void main(String[] args) {
try{
FileChannel channel = new RandomAccessFile("D:\\test.txt", "rw").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4);
while(channel.read(buffer) != -1){
buffer.flip();
while(buffer.hasRemaining()){
log.debug("{}", (char)buffer.get());
}
buffer.clear();
}
}catch (Exception e){
System.out.println(e.fillInStackTrace());
}
}
Half pack 、 Sticky package
public static ByteBuffer split(ByteBuffer source){
// Switch to read mode
source.flip();
int limit = source.limit();
for(int i=0; i<limit;i++){
//get(i) Can't move position but get() Meeting
if(source.get(i) == '\n'){
int len = i - source.position() + 1;
ByteBuffer target = ByteBuffer.allocate(len);
for(int j = source.position(); j < len; j++){
target.put(source.get());
}
target.flip();
ByteBufferUtil.debugAll(target);
source.compact();
return target;
}
}
return null;
}
3、 ... and 、FileChannel、Path、Files
( One ) Path
Path source = Paths.get("1.txt"); // Relative paths Use user.dir Environment variables to locate 1.txt
Path source = Paths.get("d:\\1.txt"); // Absolute path On behalf of d:\1.txt
Path source = Paths.get("d:/1.txt"); // Absolute path It also represents d:\1.txt
Path projects = Paths.get("d:\\data", "projects"); // On behalf of d:\data\projects
Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
System.out.println(path);
System.out.println(path.normalize()); // Normalization path
Output :
d:\data\projects\a\..\b
d:\data\projects\b
( Two ) Files
- Check if the file exists :exists(path)
- Create directory :createDirectory(path)、createDirectories(path)
- Copy files :Files.copy(source, target);
- Delete file :Files.delete(target);
Traverse the directory
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
AtomicInteger dirCount = new AtomicInteger();
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
System.out.println(dir);
dirCount.incrementAndGet();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
System.out.println(file);
fileCount.incrementAndGet();
return super.visitFile(file, attrs);
}
});
System.out.println(dirCount); // 133
System.out.println(fileCount); // 1479
}
Delete directory
Path path = Paths.get("d:\\a");
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
Files.delete(dir);
return super.postVisitDirectory(dir, exc);
}
});
版权声明
本文为[All the names I thought of were used]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231404419387.html
边栏推荐
- Wechat applet obtains login user information, openid and access_ token
- Recyclerview advanced use (II) - simple implementation of vertical drag and drop sorting
- Chrome插件 之 Selenium IDE、XPath 安装
- Indoor and outdoor map switching (indoor three-point positioning based on ibeacons)
- redis数据库讲解(三)redis数据类型
- On September 8, the night before going to Songshan Lake
- Jira截取全图
- PySide2
- 连接公司跳板机取别名
- Visio installation error 1:1935 2: {XXXXXXXX
猜你喜欢

MySQL数据库讲解(七)

Research on recyclerview details - Discussion and repair of recyclerview click dislocation

按实际取,每三级分类汇总一次,看图知需求

某政务云项目业务系统迁移调研实践

VMware15Pro在Deepin系统里面挂载真机电脑硬盘

星界边境文本自动翻译机使用说明

Call wechat customer service applet

logback-logger和root

Win10 comes with groove music, which can't play cue and ape files. It's a curvilinear way to save the country. It creates its own aimpack plug-in package, and aimp installs DSP plug-in

Storage path of mod subscribed by starbound Creative Workshop at Star boundary
随机推荐
Wechat applet positioning and ranging through low-power Bluetooth device (2)
Chrome插件 之 Selenium IDE、XPath 安装
Indoor and outdoor map switching (indoor three-point positioning based on ibeacons)
Jacob print word
redis数据库讲解二(redis高可用、持久化、性能管理)
Nifi 快速安装及文件同步操作
RobotFramework 之 项目框架
JDBC details
RobotFramework 之 文件上传和下载
postman批量生产body信息(实现批量修改数据)
PySide2
FBS (fman build system) packaging
Algorithem_ReverseLinkedList
Storage path of mod subscribed by starbound Creative Workshop at Star boundary
Wechat applet communicates with esp8266 based on UDP protocol
01-NIO基础之ByteBuffer和FileChannel
服务器日志分析工具(识别,提取,合并,统计异常信息)
HyperMotion云迁移助力中国联通,青云完成某央企上云项目,加速该集团核心业务系统上云进程
redis数据库讲解(四)主从复制、哨兵、Cluster群集
Request module