java filechannel 写文件_用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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值