public static void copyFileOrDirectory( File from_file_or_dir, File to_parent_dir ) throws IOException { if ( !from_file_or_dir.exists()){ throw( new IOException( "File '" + from_file_or_dir.toString() + "' doesn't exist" )); } if ( !to_parent_dir.exists()){ throw( new IOException( "File '" + to_parent_dir.toString() + "' doesn't exist" )); } if ( !to_parent_dir.isDirectory()){ throw( new IOException( "File '" + to_parent_dir.toString() + "' is not a directory" )); } if ( from_file_or_dir.isDirectory()){ File[] files = from_file_or_dir.listFiles(); File new_parent = new File( to_parent_dir, from_file_or_dir.getName()); FileUtil.mkdirs(new_parent); for (int i=0;i<files.length;i++){ File from_file = files[i]; copyFileOrDirectory( from_file, new_parent ); } }else{ File target = new File( to_parent_dir, from_file_or_dir.getName()); if ( !copyFile( from_file_or_dir, target )){ throw( new IOException( "File copy from " + from_file_or_dir + " to " + target + " failed" )); } } }
public static void importDownloadState( File source_dir, byte[] download_hash ) throws DownloadManagerException { String hash_str = ByteFormatter.encodeString( download_hash ); String state_file = hash_str + ".dat"; File target_state_file = new File( ACTIVE_DIR, state_file ); File source_state_file = new File( source_dir, state_file ); if ( !source_state_file.exists()){ throw( new DownloadManagerException( "Source state file missing: " + source_state_file )); } if ( target_state_file.exists()){ target_state_file.delete(); //throw( new DownloadManagerException( "Target state file already exists: " + target_state_file )); } if ( !FileUtil.copyFile( source_state_file, target_state_file )){ throw( new DownloadManagerException( "Failed to copy state file: " + source_state_file + " -> " + target_state_file )); } File source_state_dir = new File( source_dir, hash_str ); if ( source_state_dir.exists()){ try{ FileUtil.copyFileOrDirectory( source_state_dir, ACTIVE_DIR ); }catch( Throwable e ){ target_state_file.delete(); throw( new DownloadManagerException( "Failed to copy state dir: " + source_dir + " -> " + ACTIVE_DIR, e )); } } }
@Override public boolean exportState( File target_dir ) { try{ this_mon.enter(); save( true ); byte[] hash = torrent.getHash(); String hash_str = ByteFormatter.encodeString( hash ); String state_file = hash_str + ".dat"; File existing_state_file = new File( ACTIVE_DIR, state_file ); File target_state_file = new File( target_dir, state_file ); if ( !FileUtil.copyFile( existing_state_file, target_state_file )){ throw( new IOException( "Failed to copy state file" )); } File existing_state_dir = new File( ACTIVE_DIR, hash_str ); if ( existing_state_dir.exists()){ FileUtil.copyFileOrDirectory( existing_state_dir, target_dir ); } return( true ); }catch( Throwable e ){ Debug.out( e ); return( false ); }finally{ this_mon.exit(); } }