• Netty-Channel的读和写


    public class NIOFileChannel01 {
    
        public static void main(String[] args) throws Exception {
            String str = "hello,帅锅";
            //创建一个输出流->channel
            FileOutputStream fileOutputStream = new FileOutputStream("d:\file01.txt");
    
            //通过 fileOutputStream 获取 对应的 FileChannel
            //这个 fileChannel 真实 类型是  FileChannelImpl
            FileChannel fileChannel = fileOutputStream.getChannel();
    
            //创建一个缓冲区 ByteBuffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    
            //将 str 放入 byteBuffer
            byteBuffer.put(str.getBytes());
    
    
            //对byteBuffer 进行flip
            byteBuffer.flip();
    
            //将byteBuffer 数据写入到 fileChannel
            fileChannel.write(byteBuffer);
            fileOutputStream.close();
        }
    }
    public class NIOFileChannel02 {
        public static void main(String[] args) throws Exception {
    
            //创建文件的输入流
            File file = new File("d:\file01.txt");
            FileInputStream fileInputStream = new FileInputStream(file);
    
            //通过fileInputStream 获取对应的FileChannel -> 实际类型  FileChannelImpl
            FileChannel fileChannel = fileInputStream.getChannel();
    
            //创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
    
            //将 通道的数据读入到Buffer
            fileChannel.read(byteBuffer);
    
            //将byteBuffer 的 字节数据 转成String
            System.out.println(new String(byteBuffer.array()));
            fileInputStream.close();
    
        }
    }

  • 相关阅读:
    JAVA实现的异步redisclient
    权限表设计
    操作系统之存储管理(续)
    leetcode第一刷_Jump Game
    linux之stat函数解析
    重温微积分 —— 偏微分与链式法则
    重温微积分 —— 偏微分与链式法则
    所谓敏感(数字的敏感)
    所谓敏感(数字的敏感)
    推理集 —— 特殊的工具
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/14396718.html
Copyright © 2020-2023  润新知