Archive

Posts Tagged ‘java file copy’

Java: File Copy and File Move

October 7th, 2009 No comments

It has been a while since I’ve done any major Java development, it seems I have got used to having all the standard file tools which are available in scripted 4th and 5th generation languages like PHP.

Java whilst incredibly powerful is sometimes a bit awkward when dealing with certain problems. Often it’s the level abstraction and/or ability to get under the hood that can cloud a somewhat simple task, in my case file copying and moving.

Here is a small package that simplifies file copies and moves :)

package Utils.SystemTools;

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 FileCopy{
	
	public static void copy(File source,File dest) throws IOException{
		try{
			copy(source.getPath(),dest.getPath());
		} 
		catch (IOException e){
			throw e;
		}
	}
	
	public static void copy(String source,String dest) throws IOException{
		try{
			File sourceFile = new File(source);
			File destFile = new File(dest);
			InputStream in = new FileInputStream(sourceFile);
			OutputStream out = new FileOutputStream(destFile);
			
			int bufferSize = 1024;
			byte[] buf = new byte[bufferSize];
			int len;
			while ((len = in.read(buf)) > 0){
				out.write(buf,0,len);
			}
			in.close();
			out.close();
	    }
	    catch(IOException e){
	    	throw e;
	    }
	}
	
	public static void move(String source,String dest) throws IOException{
		try{
			copy(source,dest);
		}
		catch(IOException e){
			throw e;
		}
		File sourceFile = new File(source);
		if (!sourceFile.delete()){
			throw new IOException("File deletion failed for: " + source);
		}
	}

	public static void move(File source,File dest) throws IOException{
		try{
			move(source.getPath(),dest.getPath());
		}
		catch(IOException e){
			throw e;
		}
		if (!source.delete()){
			throw new IOException("File deletion failed for: " + source.getPath());
		}
	}	
	
}
Categories: Code, General, Java Tags: ,