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 lambda expression
    Domain logic approaches
    Spring AOP Capabilities ang goals
    CDI Features
    JAVA DESIGN PATTERN
    LDAP & Implementation
    spring ref &history&design philosophy
  • 原文地址:https://www.cnblogs.com/erlou96/p/13809798.html
Copyright © 2011-2022 走看看