FileChannel示例

前面我们看过socket通道,datagram通道,以管道Pipe,从今天起,我们来看一下file通道,先从一个示例开始:
测试主类1:
package nio.filechannel;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* 测试FileChannel
* @author donald
* 2017年4月9日
* 下午4:16:35
*/
public class testFileChannel {
public static void main(String[] args) throws IOException {
RandomAccessFile aFile = new RandomAccessFile("E:/nio_data.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
/*
* 1.先屏蔽writeBytes,执行readBytes,从文件中读取数据
* 2.再屏蔽readBytes,执行writeBytes,向文件中写数据
* 3.最后屏蔽writeBytes,执行readBytes,从文件中读取数据
*/
// writeBytes(buf, inChannel);
readBytes(buf, inChannel);
inChannel.close();
aFile.close();
}
private static void writeBytes(ByteBuffer buf, FileChannel fileChannel) throws IOException{
String newData = "new String to write to file...."+System.currentTimeMillis();
buf.put(newData.getBytes("UTF-8"));
buf.flip();
while(buf.hasRemaining())
fileChannel.write(buf);
System.out.println("===已经写完数据到文件");

}
private static void readBytes(ByteBuffer buf, FileChannel fileChannel) throws IOException{
buf.clear();
//从file通道读取数据到缓存区,即写入缓冲区
int bytesRead = fileChannel.read(buf);
while (bytesRead != -1) {
// buf.compact();//将未读完的数据移到缓冲的前面,新写入的数据,将会append旧数据的后面
bytesRead = fileChannel.read(buf);
}
//转换缓冲区模式
buf.flip();// swith the mode write or read
System.out.println("=====Read byte length:" + buf.limit());
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
System.out.println();
}
}

按一下三步执行:
1.先屏蔽writeBytes,执行readBytes,从文件中读取数据
2.再屏蔽readBytes,执行writeBytes,向文件中写数据
3.最后屏蔽writeBytes,执行readBytes,从文件中读取数据
相应的控制台输出为:
1.=====Read byte length:0
2.===已经写完数据到文件
3.=====Read byte length:44
new String to write to file....1494407798722

测试主类2:
package nio.filechannel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
/**
* 测试通道间传输
* @author donald
* 2017年4月9日
* 下午10:27:16
*/
public class testTransferChannel {
public static void main(String[] args) throws IOException {
RandomAccessFile fromFile = new RandomAccessFile("E:/nio_data.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("E:/nio_data_to.txt", "rw");
FileChannel toChannel = toFile.getChannel();
RandomAccessFile to2File = new RandomAccessFile("E:/nio_data_to2.txt", "rw");
FileChannel to2Channel = to2File.getChannel();
long position = 0;
long count = fromChannel.size();
//将源通道的数据传输的本通道
toChannel.transferFrom(fromChannel, position, count);
System.out.println("===将源通道的数据传输的本通道完毕");
//将本通道数据传输到目的通道
fromChannel.transferTo(position, count, to2Channel);
System.out.println("===将本通道数据传输到目的通道完毕");
fromChannel.close();
fromFile.close();
toChannel.close();
toFile.close();
to2Channel.close();
to2File.close();
}
}

控制输出:
===将源通道的数据传输的本通道完毕
===将本通道数据传输到目的通道完毕

打开文件E:/nio_data_to.txt和E:/nio_data_to2.txt,文件内容如下:
new String to write to file....1494407798722
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FileChannel的map()方法用于将文件的某个区域映射到内存中。它返回一个MappedByteBuffer对象,通过该对象可以直接操作内存中的数据,实现文件和内存之间的高效数据传输。 map()方法的参数包括映射模式、起始位置和映射长度。映射模式可以是READ_ONLY、READ_WRITE或PRIVATE,分别表示只读、读写或私有的映射。起始位置和映射长度确定了要映射的文件区域。 示例代码如下: ```java import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class FileMappingExample { public static void main(String[] args) throws Exception { RandomAccessFile file = new RandomAccessFile("example.txt", "rw"); FileChannel channel = file.getChannel(); // 映射整个文件 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size()); // 使用buffer进行操作 buffer.put(0, (byte) 'H'); buffer.put(1, (byte) 'e'); buffer.put(2, (byte) 'l'); buffer.put(3, (byte) 'l'); buffer.put(4, (byte) 'o'); // 解除映射 buffer.force(); channel.close(); } } ``` 在上述示例中,我们创建了一个RandomAccessFile对象,并通过其getChannel()方法获取了FileChannel对象。然后,我们使用map()方法将整个文件映射到内存中,并返回一个MappedByteBuffer对象。接下来,我们可以通过MappedByteBuffer对象对内存中的数据进行操作。最后,我们使用force()方法强制将数据写回到文件,并关闭FileChannel。 需要注意的是,对内存中的数据的修改会直接影响到原始文件的内容,而原始文件的修改也会反映在内存映射中。因此,在操作完内存映射后,需要调用force()方法将数据强制写回文件,以确保数据的一致性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值