分割大文件
来源:互联网 发布:linux执行sql文件 编辑:程序博客网 时间:2024/04/19 12:53
题目:将一个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就是合并之后的文件
0 0
- 分割大文件SHELL
- Python 大文件分割
- linux 分割大文件
- 大文件分割程序
- java大文件分割
- golang 大文件分割
- 大日志文件分割
- shell分割大文件
- 分割大文件
- Java分割合并大文件
- 使用split分割大文件
- Java实现大文件分割
- 大文件不断行分割
- linux 大文件分割 split
- FileUtil(大文件分割)
- split命令分割大文件
- Linux 大文件分割split
- 超级文件分割《合并》机(分割大文件)
- arcgis server 发布FeatureAccess权限的图层
- java8使用lambda对Map排序
- MySQL与安全:ACLs、账户、密码、权限、远程登录
- Linux ubuntu 基础操作(2)
- ANDROID编程规范与常用技巧
- 分割大文件
- 【MVC】AngularJs+KendoUI开发报表Demo(导出Excel和折线图)
- intellij IDEA快捷键(Windows环境下)
- java 设计模式 拦截器
- 新闻的离线下载功能仿网易之(一) 基本功能实现
- swustoj(翻煎饼)
- tws设置在图标上显示新闻
- CSDN加载图片的问题
- java 基础