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

    好了

  • 相关阅读:
    Java之内部类
    java之对象的前世今生
    java之继承
    java之接口
    何为大学 大学何为?
    丁香般的姑娘
    MySQL创建数据库与创建用户以及授权
    CentOS6.8手动安装MySQL5.6
    linux 修改myql 编码配置等信息参考
    Centos6.8 Mysql5.6 安装配置教程
  • 原文地址:https://www.cnblogs.com/erlou96/p/13809798.html
Copyright © 2011-2022 走看看