Skip navigation

Creative Commons License
I had my head banging against the wall recently with a project I am working on; what I thought would be a relatively simple task turned out to be quite the opposite, well for a new comer to Java at least: copying one directory to another using Java.

After a relentless search I came across a number of different approaches using varying techniques, all of which were either poorly documented, used out dated components, or had me reaching for my dunce hat.

I did eventually find a solution, it didn’t quite fit my needs perfectly so I have modified slightly and included within my FileUtils class which also allows directory creation; creds go to the anonymous author on exampledepot.

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {

        //Takes in String representing the full path of the target directory
	public void createDir(String paramDir){
		String directory = paramDir;
		try{
			boolean success = (
					new File(directory)).mkdir();
			if (success) {
				System.out.println("Successfuly created " + directory);
			} else {
				System.out.println("Could not create directory");
				System.out.println("Check it doesn't exist already, and the permissions ");
			}

		}catch (Exception e){
			System.err.println("Error running createDir method");
			System.err.println("Error: " + e.getMessage());
		}	
	}

        //Takes in two String representing the full path of the source and destination
	public void copyDir(String paramSourceDir, String paramTargetDir){
		File sourceDir = new File(paramSourceDir);
		File targetDir = new File(paramTargetDir);

		if (sourceDir.isDirectory()) {
			if (!targetDir.exists()) {
				targetDir.mkdir();
			}

			String[] children = sourceDir.list();
			System.out.println("Created " + targetDir.toString());
			for (int i=0; i 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
		}catch(Exception e){
			System.out.println("Error with copyFile method");
		}
	}//end copyFile()

}//end class
Advertisements

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

%d bloggers like this: