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));
        }
    }

    好了

  • 相关阅读:
    css之页面顶部阴影
    css之使用 :not() 在菜单上应用/取消应用边框
    CSS之黑白图像
    AMD/CMD规范
    HTTP学习笔记
    MUI之ajax获取后台接口数据
    Git提交代码规范
    Unicode与UTF-8/UTF-16/UTF-32的区别
    系统编程书籍推荐
    单口双线PC连接转换器 手机电脑耳机转接线
  • 原文地址:https://www.cnblogs.com/erlou96/p/13809798.html
Copyright © 2011-2022 走看看