java filechannel 写文件_java filechannel大文件的读写

这篇博客介绍了使用Java的FileChannel和MappedByteBuffer高效读取大文件的方法,特别是通过映射文件到内存的中间区域,避免内存溢出。内容包括不同方式的读取策略,如按固定大小缓冲区读取和映射文件的一半内容。
摘要由CSDN通过智能技术生成

java 读取一个巨大的文本文件既能保证内存不溢出又能保证性能

2010-09-25 11:18:50|  分类: 默认分类 |字号 订阅

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

public class ReadBig {

public static String fff = "C:\\mq\\read\\from.xml";

public static void main1(String[] args) throws Exception {

final int BUFFER_SIZE = 0x300000;// 缓冲区大小为3M

File f = new File(fff);

/**

*

* map(FileChannel.MapMode mode,long position, long size)

*

* mode - 根据是按只读、读取/写入或专用(写入时拷贝)来映射文件,分别为 FileChannel.MapMode 类中所定义的

* READ_ONLY、READ_WRITE 或 PRIVATE 之一

*

* position - 文件中的位置,映射区域从此位置开始;必须为非负数

*

* size - 要映射的区域大小;必须为非负数且不大于 Integer.MAX_VALUE

*

* 所以若想读取文件后半部分内容,如例子所写;若想读取文本后1/8内容,需要这样写map(FileChannel.MapMode.READ_ONLY,

* f.length()*7/8,f.length()/8)

*

* 想读取文件所有内容,需要这样写map(FileChannel.MapMode.READ_ONLY, 0,f.length())

*

好的,我可以为您提供一个示例代码,将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(); } } } ``` 这两个示例代码分别用于读取和文件。您可以根据自己的需求进行修改和扩展。记得替换文件名和路径以适应您的实际情况。希望对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值