NIO – File Channel代码示例

package player.kent.chen.temp.learnnio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class PlayFileChannel {

    public static void main(String[] args) throws IOException {

        playOutput();
        playInput();

    }

    private static void playOutput() throws FileNotFoundException, IOException {
        FileChannel fc = new FileOutputStream("/home/kent/temp/data.txt").getChannel();
        ByteBuffer buff = ByteBuffer.wrap("All the data".getBytes());
        fc.write(buff);
        fc.close();
    }

    private static void playInput() throws FileNotFoundException, IOException {
        FileChannel fc = new FileInputStream("/home/kent/temp/data.txt").getChannel();
        ByteBuffer buff = ByteBuffer.allocate(1024);
        fc.read(buff); //把文件内容读出来,写到buffer中  
        buff.flip(); //让buffer进入“可读”状态
        while (buff.hasRemaining()) {
            System.out.println((char) buff.get());
        }
    }

}


Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.