当前位置:网站首页>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
 Insert picture description here
 Insert picture description here

Reading mode

 Insert picture description here
 Insert picture description here

Write mode ----> Reading mode : flip()
Reading mode ----> Write mode :clear()、compact()

( One ) compact and clear The difference between

clear
 Insert picture description here
compact
 Insert picture description here

( 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