版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/luo4105/article/details/73650036
文件通道FileChannel,是堵塞的。作用是文件的连接和读取。
FileChannel不能直接打开,我们可以使用RandomAccessFile、InputStream、OutputStream来获取FileChannel实例。下面是RandomAccessFile获取实例
RandomAccessFile aFile = new RandomAccessFile("nio-data.txt","rw");
FileChannel inChannel = aFile.getChannel();
可以使用Buffer缓存来读写数据
ByteBuffer bBuffer = ByteBuffer.allocate(48);
int readSize;
do {
readSize = fileChannel.read(bBuffer);
bBuffer.flip();
System.out.println(Charset.forName("UTF-8").decode(bBuffer));
bBuffer.clear();
} while (readSize != -1);
String newData = "\nNewString to write to file..." + System.currentTimeMillis();
ByteBuffer bBuffer = ByteBuffer.allocate(48);
fileChannel.position(fileChannel.size()); // 定位末尾,接着输入
bBuffer.put(newData.getBytes("UTF-8"));
bBuffer.clear();
while (bBuffer.hasRemaining()){
fileChannel.write(bBuffer);
}
bBuffer.flip();
FileChannel的size方法可以获得实例返回的文件大小。如:
long fileSize= channel.size();
FileChannel的truncate方法可以截取文件。截取文件时,文件将指定长度后面的部分将被删除。
channel.truncate(1024);
这个例子截取文件的前1024个字节。
FileChannel的force方法可以将通道中的缓存数据强制写到硬盘上,在操作系统中默认写入是调用write(),但是它会有缓存存在,可以调用sync和fsync函数,它会把缓存的数据强制写入。如:
channel.force(true);
public classFileChannelTest {
private RandomAccessFile accessFile;
private FileChannel fileChannel;
FileChannelTest(){
try {
accessFile = new RandomAccessFile("nio-data.txt","rw");
fileChannel = accessFile.getChannel();
}catch(FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* FileChannel读数据
*/
public void readFileChannel() {
try {
ByteBufferbBuffer= ByteBuffer.allocate(48);
int readSize;
do {
readSize = fileChannel.read(bBuffer);
bBuffer.flip();
System.out.println(Charset.forName("UTF-8").decode(bBuffer));
bBuffer.clear();
}while(readSize!= -1);
}catch(IOException e) {
e.printStackTrace();
}finally{
try {
fileChannel.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
/**
* FileChannel写数据
*/
public void writeFileChannel() {
try {
StringnewData= "\nNew String to write tofile..." + System.currentTimeMillis();
ByteBufferbBuffer= ByteBuffer.allocate(48);
fileChannel.position(fileChannel.size()); // 定位末尾,接着输入
bBuffer.put(newData.getBytes("UTF-8"));
bBuffer.clear();
while (bBuffer.hasRemaining()) {
fileChannel.write(bBuffer);
}
bBuffer.flip();
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{
try {
fileChannel.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
FileChannelTestwriteCannel= newFileChannelTest();
writeCannel.writeFileChannel();
FileChannelTestreadCannel= newFileChannelTest();
readCannel.readFileChannel();
}
}