Recently, the company project needs to split a large file into several small files for processing, after processing, all the small files are merged into one file.
Sample code
Package com.xx.test;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.nio.channels.FileChannel;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Comparator;
Import java.util.List;
Import Org.junit.Test;
public class Filecombinetest {@Test public void Test () {String Dirpath = "d:/fbb/myworkspace_dw/finaldb/";
File dir = new file (Dirpath);
list<file> files = new arraylist<file> ();
For (File tmpFile:dir.listFiles ()) {if (Tmpfile.getname (). StartsWith ("Abc_")) {Files.add (tmpfile);
To sort the collection of files (the order that affects the subsequent file merges) Collections.sort (Files, new Namecomparator ());
try {//abc_1.txt,abc_2.txt--> abc.txt combinefiles (Files,dirpath, "abc.txt");
catch (IOException e) {e.printstacktrace ();
/** * Merge all files under the specified directory * @param files * @param dirpath * @param savefilename * @throws IOException * * public void CombInefiles (list<file> files, String dirpath,string savefilename) throws IOException {if (Files==null | |
Files.size () <1) {throw new RuntimeException ("The file to be merged does not exist ...");
} File OutputFile = new file (dirpath+savefilename);
if (!outputfile.exists ()) {outputfile.createnewfile ();
} filechannel Outchannel = new FileOutputStream (outputfile). Getchannel ();
FileChannel Inchannel;
for (file file:files) {Inchannel = new FileInputStream (file). Getchannel ();
Inchannel.transferto (0, Inchannel.size (), Outchannel);
Inchannel.close ();
} outchannel.close ();
Private class Namecomparator implements comparator<file>{@Override public int Compare (file f1, file F2) {
Return F1.getname (). CompareTo (F2.getname ());
}
}
}
It's done, hoo.