java实现大文件分割与合并的实例代码
本文导语: 代码如下:package com.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import ...
package com.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
public class LargeMappedFiles {
/**
* 大数据排序合并
*
* @param args
*/
public static void main(String[] args) throws IOException {
// 写入文件的路径
String filePath = "D:\456";
// 切分文件的路径
String sqlitFilePath = "D:\456\123";
//数据的个数
int CountNumbers=10000000;
//子文件的个数
int CountFile=10;
//精度
int countAccuracy=30*CountFile;
long startNumber=System.currentTimeMillis();
// 写入大数据文件
WriteData(filePath,CountNumbers);
System.out.println("存储完毕");
// 将大数据文件切分到另外的十个小文件中
sqlitFileDate(filePath, sqlitFilePath,CountFile);
System.out.println("文件切割完毕!");
// 把每个文件的数据进行排序
singleFileDataSort(sqlitFilePath,CountFile);
System.out.println("每个子文件排序完毕!");
//精度调整,十个文件数据进行比较整合
deathDataFile(filePath,sqlitFilePath,countAccuracy,CountFile);
System.out.println("整合完毕");
long stopNumber=System.currentTimeMillis();
System.out.println("耗时"+(stopNumber-startNumber)/1000+"毫秒");
}
// 写入大数据文件
public static void WriteData(String path,int CountNumbers) throws IOException {
path = path + "\12114.txt";
FileWriter fs = new FileWriter(path);
BufferedWriter fw=new BufferedWriter(fs);
for (int i = 0; i < CountNumbers; i++) {
fw.write(new Random().nextInt(Integer.MAX_VALUE) + "rn");
}
fw.close();
fs.close();
}
// 将大数据文件切分到另外的十个小文件中
public static void sqlitFileDate(String filepath, String sqlitPath,
int CountFile) throws IOException {
FileWriter fs = null;
BufferedWriter fw=null;
FileReader fr = new FileReader(filepath + "\12114.txt");
BufferedReader br = new BufferedReader(fr); // 读取获取整行数据
int i = 1;
LinkedList WriterLists=new LinkedList(); //初始化文件流对象集合
LinkedList fwLists=new LinkedList();
for (int j = 1; j = CountFile) {
i = 1;
} else
i++;
}
br.close();
fr.close();
for (Iterator iterator = fwLists.iterator(); iterator.hasNext();) {
BufferedWriter object = (BufferedWriter) iterator.next();
object.close();
}
//遍历关闭所有子文件流
for (Iterator iterator = WriterLists.iterator(); iterator.hasNext();) {
FileWriter object = (FileWriter) iterator.next();
object.close();
}
}
// 把每个文件的数据进行排序
public static void singleFileDataSort(String path1,int CountFile) throws IOException {
LinkedList nums = null;
for (int i = 1; i