java - Combining all text files in a folder into a single file -


how can combine txt files in folder single file? folder contains hundreds thousands of txt files.

if program run on windows machines go batch file containing like

copy /b *.txt merged.txt

but not case, figured might easier write in java complement else have.

i have written this

// retrieves list of files specified folder filter applied file[] files = utils.filterfiles(downloadfolder + folder, ".*\\.txt"); try {   // savepath path of output file   fileoutputstream outfile = new fileoutputstream(savepath);    (file file : files)   {       fileinputstream infile = new fileinputstream(file);       integer b = null;       while ((b = infile.read()) != -1)           outfile.write(b);       infile.close();   }   outfile.close(); } catch (exception e) {   e.printstacktrace(); } 

but takes several minutes combine thousands of files not feasible.

because of this

  integer b = null;   while ((b = infile.read()) != -1)       outfile.write(b); 

your os making lot of io calls. read() reads 1 byte of data. use other read methods accept byte[]. can use byte[] write outputstream. write(int) io call writing single byte. change too.

of course, can tools you, apache commons io or java 7 nio package.


Comments