zoukankan      html  css  js  c++  java
  • nio channel demo

    下面的是nio channel的demo

    import java.nio.channels.FileChannel;
    
    public class NioFileChannelTest {
        public static void main(String[] args) throws Exception{
    
            // 创建一个字符串
            String str = new String("你好,nio");
    
            // 创建一个文件输出流
            File file = new File("F://test.txt");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
    
            // 通过文件输出流,创建一个filechannel
            FileChannel channel = fileOutputStream.getChannel();
    
            // 创建一个bytebuffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
    
            // 将str put到buffer中
            buffer.put(str.getBytes());
    
            // 将buffer 翻转
            buffer.flip();
    
            // 将buffer写入到channel中,write和read 是针对channel来说的
            channel.write(buffer);
    
            fileOutputStream.close();
        }
    }

    注意点:一个utf-8的汉子 占用3个字节

    读取channel数据的demo

    public class NioFileChannelTest2 {
        public static void main(String[] args) throws Exception{
    
            File file = new File("F://test.txt");
            FileInputStream fileInputStream = new FileInputStream(file);
    
            ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length());
    
            FileChannel channel = fileInputStream.getChannel();
    
            channel.read(byteBuffer);
    
            byteBuffer.flip();
    
            byte[] array = byteBuffer.array();
    
            System.out.println(new String(array));
        }
    }

    好了

  • 相关阅读:
    今天不谈技术,谈感情~
    外派金融公司
    OAuth2-简介
    Zookeeper实战-分布式锁
    Zookeeper-基础
    Minio-对象存储
    Redis实战-BloomFilter
    Redis实战-详细配置-优雅的使用Redis注解/RedisTemplate
    Redis-基础
    SpringBoot-表单验证-统一异常处理-自定义验证信息源
  • 原文地址:https://www.cnblogs.com/erlou96/p/13809798.html
Copyright © 2011-2022 走看看