题目:将一个10亿个随机整数的txt文件分割成100个文件。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Random;
/**
* @author Hutongling
*
* @time:2017年4月11日 下午3:13:15
*/
public class 分割大文件 {
// 拆分文件
static void cut() {
File file = new File("D:\\data.txt");
int num = 100;// 分割文件的数量
long lon = file.length() / num + 1L;// 使文件字节数+1,保证取到所有的字节
try {
RandomAccessFile raf1 = new RandomAccessFile(file, "r");
byte[] bytes = new byte[1024];// 值设置越小,则各个文件的字节数越接近平均值,但效率会降低,这里折中,取1024
int len = -1;
for (int i = 0; i < num; i++) {
String name = "D:\\data\\source" + i + ".txt";
File file2 = new File(name);
RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");
while ((len = raf1.read(bytes)) != -1) {// 读到文件末尾时,len返回-1,结束循环
raf2.write(bytes, 0, len);
if (raf2.length() > lon)// 当生成的新文件字节数大于lon时,结束循环
break;
}
raf2.close();
}
raf1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 合并文件
static void merge() {
File file = new File("D:\\data\\new.txt");
try {
RandomAccessFile target = new RandomAccessFile(file, "rw");
for (int i = 0; i < 100; i++) {
File file2 = new File("D:\\data\\source" + i + ".txt");
RandomAccessFile src = new RandomAccessFile(file2, "r");
byte[] bytes = new byte[1024];// 每次读取字节数
int len = -1;
while ((len = src.read(bytes)) != -1) {
target.write(bytes, 0, len);// 循环赋值
}
src.close();
}
target.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Random random=new Random();
String path="D:/data.txt";
File text=new File(path);
FileWriter textFile=new FileWriter(text);
int n=1000000000;
for(int i=0;i<n;i++)
if((i+1)%1000!=0)
textFile.write(random.nextInt(1000000000) + " ");
else
textFile.write(random.nextInt(1000000000) + "\n");
cut();
merge();
}
}
十亿数据大概有9.5个G左右。
图中的source0.txt~source99.txt就是分割出来的小文件,第一个new.txt就是合并之后的文件