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

posted on 2016-07-19 11:05  james-roger  阅读(122)  评论(0编辑  收藏  举报