`
H小阿飞
  • 浏览: 274911 次
  • 性别: Icon_minigender_1
  • 来自: 南通
社区版块
存档分类
最新评论

用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();

    }

}

 

0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics