Java FileChannel读写文件例子

在Java NIO包中FileChannel是用于读取、写入、映射和操作文件的通道。

下面通过利用FileChannel来进行文件的读写例子

1从txt文件中读取数据并且输出到控制台

public static void main(String[] args) throws IOException {
		/*需要通过 FileInputStream、FileOutputStream 或 RandomAccessFile对象来获取FileChannel
		 * */
		FileInputStream f1 = new FileInputStream("b.txt"); 
		FileChannel fc1 = f1.getChannel();
		ByteBuffer b1 = ByteBuffer.allocate(25);//初始化缓冲区大小
		fc1.read(b1);//将文件通道里面的字节读到缓冲区中
		b1.flip();//此方法将position置为0,limit放到position位置
		while(b1.hasRemaining()) {// position<limit时返回true
			System.out.println((char)b1.get());
		}
		fc1.close();//关闭通道
	}
此例子有两点细节:

第一 在使用fc1.read(b1)后此时缓冲区内的position(当前读取位置)和limit(读写上限的位置)是一样的,可以调用ByteBuffer的position()方法和limit()方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以为您提供一个示例代码,将JavaFileChannel和MappedByteBuffer用于读写文件,并将和写的代码分开。请参考以下示例: 首先,我们来看一下文件的代码: ```java import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class FileReader { public static void main(String[] args) { try { // 打开文件 RandomAccessFile file = new RandomAccessFile("input.txt", "r"); FileChannel channel = file.getChannel(); // 将文件映射到内存中 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); // 文件内容 while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } // 关闭文件 channel.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 接下来,我们来看一下写入文件的代码: ```java import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class FileWriter { public static void main(String[] args) { try { // 打开文件 RandomAccessFile file = new RandomAccessFile("output.txt", "rw"); FileChannel channel = file.getChannel(); // 将文件映射到内存中 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024); // 写入数据到缓冲区 String data = "Hello, World!"; buffer.put(data.getBytes()); // 刷新缓冲区到文件 buffer.force(); // 关闭文件 channel.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这两个示例代码分别用于取和写入文件。您可以根据自己的需求进行修改和扩展。记得替换文件名和路径以适应您的实际情况。希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值