• Java NIO


    读取指定文件的类容:

    package com.nio;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    
    public class FileInputStreamTest {
    
        public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            File file = new File("d:\reader.txt");
            FileInputStream in = new FileInputStream(file);
            FileChannel channel = in.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
            
            channel.read(buffer);
            buffer.rewind();
            byte[] b = buffer.array();
            System.out.println(new String(b));
            
            channel.close();
            in.close();
        }
    
    }

    文件拷贝:

    package com.nio;
    
    import java.io.FileInputStream;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    
    public class CopyFileTest {
    
        public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            FileInputStream fin = new FileInputStream("d:\reader.txt");
            FileOutputStream fout = new FileOutputStream("d:\nioTest.txt");
            FileChannel inChannel = fin.getChannel();
            FileChannel outChannel = fout.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(128);
            while(true){
                buffer.clear();
                int r = inChannel.read(buffer);
                if(r==-1){
                    break;
                }
                buffer.flip();
                outChannel.write(buffer);
            }
            outChannel.close();
            inChannel.close();
            fout.close();
            fin.close();
        }
    
    }

     参考文档:http://ifeve.com/buffers/

    socket:http://blog.csdn.net/kongxx/article/details/7288896

    http://developer.51cto.com/art/201112/306363.htm

  • 相关阅读:
    网络协议 19
    网络协议 18
    网络协议 17
    网络协议 16
    网络协议 15
    .NET基础知识(01)-值类型与引用类型
    .NET基础知识(02)-拆箱与装箱
    网络协议 14
    网络协议 13
    网络协议 12
  • 原文地址:https://www.cnblogs.com/james-roger/p/5683948.html
Copyright © 2020-2023  润新知