package com.tutego.insel.solutions.io;

import java.io.*;

public class FileCopy
{
  public static void main( String args[] )
    {
//    System.out.println( fileCopy( "c:/test.txt", "c:/blub.txt" ) );
    
    insertFile( "c:/test.txt" );
  }
  
  public static void insertFile( String sourceFile )
  {
    File forg = new File( sourceFile );
    
    String path = forg.getParent(), name = forg.getName();
    
    File fcopy = new File( path, "Kopie von " + name );
    
    // gibt's fcopy schon?
    
    int i = 2;

    while ( fcopy.exists() )
      fcopy = new File( path, "Kopie (" + (i++) + ") von " + name );
    
    fileCopy( forg, fcopy );
  }
  
  public static boolean fileCopy( File sourceFile, File destFile )
  {
    try
    {
      FileInputStream in = new FileInputStream(sourceFile);
      FileOutputStream out = new FileOutputStream(destFile);

      byte buf[] = new byte[4096];
      
      int len;
      while ( (len = in.read(buf)) > 0 )
        out.write( buf, 0, len );
      
      out.close();
      in.close();
    }
    catch ( IOException e )
    {
      return false;
    }
    return true;
  }
  
  public static boolean fileCopy( String sourceFile, String destFile )
  {
    return fileCopy( new File(sourceFile), new File(destFile) );
  }
}
