读书人

用FileChannel读写资料

发布时间: 2012-10-09 10:21:45 作者: rapoo

用FileChannel读写文件

package main; import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.charset.Charset;/** * Page 502 * @author 阿飞 * 用FileChannel读写文件 * */public class FileChannelTester {     public static void main(String args[])throws IOException{       final int BSIZE=1024;       //向文件中写数据       FileChannel fc = new FileOutputStream("D:\\test.txt").getChannel();       fc.write(ByteBuffer.wrap("你好,".getBytes()));       fc.close();              //向文件末尾添加数据           //先按照“rw”访问模式打开D:\\test.txt文件,如果这个文件还不存在,RandomAccessFile的构造方法会创建该文件           fc = new RandomAccessFile("D:\\test.txt","rw").getChannel(); //RandomAccessFile不支持只写模式,因为把参数设为“w”是非法的             fc.position(fc.size());        //定位到文件末尾       fc.write(ByteBuffer.wrap("朋友!".getBytes()));       fc.close();              //读数据       fc = new FileInputStream("D:\\test.txt").getChannel();   //或者用下面的方法//      fc = new RandomAccessFile("D:\\test.txt","r").getChannel();       ByteBuffer buff = ByteBuffer.allocate(BSIZE);       fc.read(buff);       buff.flip();       Charset  cs = Charset.defaultCharset();              System.out.println(cs.decode(buff));       fc.close();    }}

?

读书人网 >编程

热点推荐