当前位置:网站首页>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
边栏推荐
猜你喜欢
使用DialogFragment的一些感受及防踩坑经验(getActivity、getDialog为空,cancelable无效等)
利用json-server在本地创建服务器请求
Promtail + Loki + Grafana 日志监控系统搭建
Easyexcel读取excel表地理位置数据,按中文拼音排序
基於CM管理的CDH集群集成Phoenix
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
Chrome插件 之 Selenium IDE、XPath 安装
教育行业云迁移最佳实践:海云捷迅使用HyperMotion云迁移产品为北京某大学实施渐进式迁移,成功率100%
某政务云项目业务系统迁移调研实践
随机推荐
报表FCRA考试题集及答案(错了11题)
数据库DbVisualizer Pro报文件错误,导致数据连接失败
POI operation word template replaces data and exports word
MySQL数据库讲解(七)
Promtail + Loki + Grafana 日志监控系统搭建
JDBC详解
Chrome插件 之 Selenium IDE、XPath 安装
Recyclerview advanced use (I) - simple implementation of sideslip deletion
RobotFramework 之 用例执行
Understand the concepts of virtual base class, virtual function and pure virtual function (turn)
多云数据流转?云上容灾?年前最后的价值内容分享
leetcode--357. Count the number of different figures
GFS分布式文件系统(理论)
Gartner预测云迁移规模大幅增长;云迁移的优势是什么?
Research on recyclerview details - Discussion and repair of recyclerview click dislocation
Wechat applet obtains login user information, openid and access_ token
Idea控制台乱码解决
RobotFramework 之 公共变量
Postman的安装使用及填坑心得
rsync+inotify远程同步