001 /** 002 * iFish - An iRiver iHP jukebox database creation tool 003 * 004 * Copyright (C) 2009 Richard "Shred" Körber 005 * http://ifish.shredzone.org 006 * 007 * This program is free software: you can redistribute it and/or modify 008 * it under the terms of the GNU General Public License as published by 009 * the Free Software Foundation, either version 3 of the License, or 010 * (at your option) any later version. 011 * 012 * This program is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 015 * GNU General Public License for more details. 016 * 017 * You should have received a copy of the GNU General Public License 018 * along with this program. If not, see <http://www.gnu.org/licenses/>. 019 */ 020 package net.shredzone.ifish; 021 022 import java.io.File; 023 024 /** 025 * Some common iFish utility functions. 026 * 027 * @author Richard Körber <dev@shredzone.de> 028 * @version $Id: Util.java 291 2009-04-28 21:29:27Z shred $ 029 */ 030 public final class Util { 031 032 private Util() {} 033 034 /** 035 * Renames a file to a new name. 036 * <p> 037 * This function shouldn't be required, but the Sun VM is buggy and 038 * might refuse to rename a file for no apparent reasons. Due to the 039 * workaround, renaming might take slightly more time. 040 * 041 * @param oldName File to be renamed 042 * @param newName New name of the file 043 * @return true: rename was successful. 044 */ 045 public static boolean renameFile( File oldName, File newName ) { 046 if( oldName.renameTo( newName ) ) return true; 047 048 // *sigh* 049 // There are one or two bugs that might result in renameTo() failing 050 // for no certain reason on Windows machines. Both are known and 051 // actively ignored by Sun. 052 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4017593 053 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298 054 // We are doing some esoteric stuff here which might help in most 055 // of the cases. 056 057 // First attempt is to delete the target file, in case it existed. 058 if( newName.exists() ) { 059 newName.delete(); 060 System.gc(); 061 try { 062 Thread.sleep(50); 063 }catch( InterruptedException ignore ) {} 064 } 065 066 // Now try 20 times to rename the file, always suggesting a GC 067 // meanwhile... Boy, this sucks! 068 for( int cnt=0; cnt<20; cnt++ ) { 069 if( oldName.renameTo( newName ) ) return true; 070 System.gc(); 071 try { 072 Thread.sleep(50); 073 }catch( InterruptedException ignore ) {} 074 } 075 076 // All our magic didn't help. Maybe the file really cannot be renamed? 077 // Sadly, Java's File.renameTo() does not report the reason why the 078 // renaming failed. 079 return false; 080 } 081 082 }