
package jp.riken.brain.ni.samuraigraph.application;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 
 * This class provides static methods for the application.
 */
public class SGApplicationUtility
{

	/**
	 * Delete all files recursively.
	 * @param f The abstract pathname to be deleted.
	 */
	public static void deleteRecursively( final File f )
	{
		if( f.isDirectory() )
		{
			String dir = f.getAbsolutePath();
			String[] fList = f.list();
			for( int ii=0; ii<fList.length; ii++ )
			{
				File f_ = new File( f+"\\"+fList[ii] );
				deleteRecursively( f_ );
			}
		}

		f.delete();
	}
	

	/**
	 * Delete all files recursively when the virtual machine terminates.
	 * @param f The abstract pathname to be deleted.
	 */
	public static void deleteOnExitRecursively( final File f )
	{
		if( f.isDirectory() )
		{
			String dir = f.getAbsolutePath();
			String[] fList = f.list();
			for( int ii=0; ii<fList.length; ii++ )
			{
				File f_ = new File( f+"\\"+fList[ii] );
				deleteOnExitRecursively( f_ );
			}
		}

		f.deleteOnExit();
	}



	/**
	 * Copy file from f1 to f2.
	 * @param f1
	 * @param f2
	 * @return true:success, false:failure
	 */
	public static boolean copyBinaryFile( final String f1, final String f2 )
		throws IOException
	{

		FileInputStream in = null;
		FileOutputStream out = null;
		try
		{
			in = new FileInputStream(f1);
			out = new FileOutputStream(f2);
		}
		catch( FileNotFoundException ex )
		{
			if( in!=null )
			{
				in.close();
			}
			if( out!=null )
			{
				out.close();
			}
			return false;
		}

		final int bufferLength = 1024;
		byte[] buffer = new byte[bufferLength];
		int len;
		while( (len=in.read(buffer,0,bufferLength))!=-1 )
		{
			out.write( buffer, 0, len );
		}


		// close I/O streams
		in.close();
		out.close();		
		
		return true;	
	}



	/**
	 * Copy file from f1 to f2.
	 * @param f1
	 * @param f2
	 * @return true:success, false:failure
	 */
	public static boolean copyBinaryFile( final File f1, final File f2 )
		throws IOException
	{
		if( f1==null || f2==null )
		{
			throw new IllegalArgumentException("f1==null || f2==null");
		}
		
		String path1 = f1.getAbsolutePath();
		String path2 = f2.getAbsolutePath();
		return copyBinaryFile(path1,path2);
	}

}

