NIO的基本应用

来源:互联网 发布:wifi广告路由器软件 编辑:程序博客网 时间:2024/05/29 07:34

对文件进行读写:

package dqd.io;import java.io.BufferedInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import org.omg.CORBA.Request;/** * NIO入门 * @author dqd */public class TestIO {public static void main(String[] args) throws IOException  {RandomAccessFile aFile = new RandomAccessFile("log/sys.out.txt", "rw");FileChannel inChannel = aFile.getChannel();ByteBuffer buf = ByteBuffer.allocate(48);int size = inChannel.read(buf);System.out.println(size);int totalSize = (int) inChannel.size();String newData = "New String to write to file..." + System.currentTimeMillis();buf = ByteBuffer.allocate(148);buf.put(newData.getBytes());buf.flip();//将可能存在缓冲区的数据强制的放入磁盘上inChannel.force(true);//一个汉字两个字节inChannel.position(totalSize);while(buf.hasRemaining()){inChannel.write(buf);}//注意关闭inChannel.close();}}