Java实现按行分割大文件
黄晓宇 人气:0简介
工作的时候,需要将一个大的文本文件按行分割成几个小文件。本来懒得写,想网上copy一下得了,但是 google 了一遍,找了几个代码写的有点乱,尝试了之后发现效率太慢了,一个 1000000 行 200M 的文件,按每个文件 2000 行分割,要6分多钟才能跑完。没办法自己写了个,试了几次,基本都是 4 秒内跑完,贴出来记录下,下次用就直接 copy 出来用。
代码
public static List<File> splitDataToSaveFile(int rows, File sourceFile, String targetDirectoryPath) { long startTime = System.currentTimeMillis(); List<File> fileList = new ArrayList<>(); log.info("开始分割文件"); File targetFile = new File(targetDirectoryPath); if (!sourceFile.exists() || rows <= 0 || sourceFile.isDirectory()) { return null; } if (targetFile.exists()) { if (!targetFile.isDirectory()) { return null; } } else { targetFile.mkdirs(); } try (FileInputStream fileInputStream = new FileInputStream(sourceFile); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { StringBuilder stringBuilder = new StringBuilder(); String lineStr; int lineNo = 1, fileNum = 1; while ((lineStr = bufferedReader.readLine()) != null) { stringBuilder.append(lineStr).append("\r\n"); if (lineNo % rows == 0) { File file = new File(targetDirectoryPath + File.separator + fileNum + sourceFile.getName()); writeFile(stringBuilder.toString(), file); //清空文本 stringBuilder.delete(0, stringBuilder.length()); fileNum++; fileList.add(file); } lineNo++; } if ((lineNo - 1) % rows != 0) { File file = new File(targetDirectoryPath + File.separator + fileNum + sourceFile.getName()); writeFile(stringBuilder.toString(), file); fileList.add(file); } long endTime = System.currentTimeMillis(); log.info("分割文件结束,耗时:{}秒", (endTime - startTime) / 1000); } catch (Exception e) { log.error("分割文件异常", e); } return fileList; } private static void writeFile(String text, File file) { try ( FileOutputStream fileOutputStream = new FileOutputStream(file); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter, 1024) ) { bufferedWriter.write(text); } catch (IOException e) { e.printStackTrace(); } }
加载全部内容