Uncategorized

Java concat files

Snippet to concat several files into a new one with Java:

import org.apache.commons.io.IOUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

...

OutputStream destinationStream = null;
InputStream is = null;

File fileDir = new File("path_to_directory");
File destination = new File("path_to_destination");

try {
   destinationStream = new BufferedOutputStream(new FileOutputStream(destination));
   for (File file: fileDir.listFiles()){
      try{
         is = new BufferedInputStream(new FileInputStream(file));
         IOUtils.copy(is, destinationStream);
         destinationStream.write("\n".getBytes()); //Separate files
      } finally {
         IOUtils.closeQuietly(is);
      }
   }
} finally {
   IOUtils.closeQuietly(destinationStream);
}

Enjoy it!

Advertisements
Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s