日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java写大文件_java实现超大文件的读写功能

發布時間:2024/10/14 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java写大文件_java实现超大文件的读写功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

對于幾百M或上G的大文件可使用java nio進行讀寫 , 根據個人的需求 可能需要將一個超大文件讀寫形成很多較小的文件進行分析,這也不是什么難事,在讀完一個緩沖區后 更換寫入的對象即可,本文就不做詳細介紹了,有需要的可以聯系本人。

直接上程序吧

package cn.gzu.readfile;

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class ReadWriteNio {

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

int bufSize = 100;

File fin = new File("E:\\jiahui\\2014-09-01.dat");

File fout = new File("E:\\jiahui\\res.txt");

System.out.print("開始讀取并重寫文件,請等待...");

FileChannel fcin = new RandomAccessFile(fin, "r").getChannel();

ByteBuffer rBuffer = ByteBuffer.allocate(bufSize);

FileChannel fcout = new RandomAccessFile(fout, "rws").getChannel();

ByteBuffer wBuffer = ByteBuffer.allocateDirect(bufSize);

readFileByLine(bufSize, fcin, rBuffer, fcout, wBuffer);

System.out.print("讀寫完成!");

}

/*讀文件同時寫文件*/

public static void readFileByLine(int bufSize, FileChannel fcin, ByteBuffer rBuffer,

FileChannel fcout, ByteBuffer wBuffer){

String enterStr = "\n";

try{

byte[] bs = new byte[bufSize];

int size = 0;

StringBuffer strBuf = new StringBuffer("");

while((size = fcin.read(rBuffer)) != -1){

// while(fcin.read(rBuffer) != -1){

if(size > 1*1024){

break;

}

int rSize = rBuffer.position();

rBuffer.rewind();

rBuffer.get(bs);

rBuffer.clear();

String tempString = new String(bs, 0, rSize,"UTF-8");

// System.out.println(size+": "+tempString);

int fromIndex = 0;

int endIndex = 0;

while((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1){

String line = tempString.substring(fromIndex, endIndex);

line = new String(strBuf.toString() + line + "\n");

System.out.println(size+": "+line);

//System.out.print("");

//write to anthone file

writeFileByLine(fcout, wBuffer, line);

strBuf.delete(0, strBuf.length());

fromIndex = endIndex + 1;

}

if(rSize > tempString.length()){

strBuf.append(tempString.substring(fromIndex, tempString.length()));

}else{

strBuf.append(tempString.substring(fromIndex, rSize));

}

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/*寫文件*/

public static void writeFileByLine(FileChannel fcout, ByteBuffer wBuffer, String line){

try {

//write on file head

//fcout.write(wBuffer.wrap(line.getBytes()));

//wirte append file on foot

fcout.write(wBuffer.wrap(line.getBytes()), fcout.size());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

總結

以上是生活随笔為你收集整理的java写大文件_java实现超大文件的读写功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。