Home >Java >javaTutorial >How to merge multiple files in java
In actual projects, when processing larger files, the files are often split into multiple sub-files for processing, and finally these sub-files are merged. Below I will introduce to you how to merge multiple files in Java.
The easiest way to think of merging sub-files in Java is to use BufferedStream for reading and writing.
The specific implementation method is as follows. The code is very detailed for your reference and study.
1. First create the mergeFiles method, receive the string array and string parameters, and complete the file merging function
public static boolean mergeFiles(String[] fpaths, String resultPath) { if (fpaths == null || fpaths.length < 1 || TextUtils.isEmpty(resultPath)) { return false; } if (fpaths.length == 1) { return new File(fpaths[0]).renameTo(new File(resultPath)); } File[] files = new File[fpaths.length]; for (int i = 0; i < fpaths.length; i ++) { files[i] = new File(fpaths[i]); if (TextUtils.isEmpty(fpaths[i]) || !files[i].exists() || !files[i].isFile()) { return false; } } File resultFile = new File(resultPath); try { int bufSize = 1024; BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(resultFile)); byte[] buffer = new byte[bufSize]; for (int i = 0; i < fpaths.length; i ++) { BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(files[i])); int readcount; while ((readcount = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, readcount); } inputStream.close(); } outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } for (int i = 0; i < fpaths.length; i ++) { files[i].delete(); } return true; }
2. Then The mergeFiles method is called in the main function. When used, the address array of multiple files is passed in, and the output file address is passed in.
public static void main(String[] args) { mergeFiles(new String[]{"D:/in_1.txt", "D:/in_2.txt", "D:/in_3.txt"}, "D:/output.txt"); }
(Related video tutorial sharing: java video tutorial)
The above is the detailed content of How to merge multiple files in java. For more information, please follow other related articles on the PHP Chinese website!