package latexDraw.util;
import java.io.*;
/**
* Defines some workarounds to deal with the problem of the renameto function.
* The renameto function cannot rename a file from one filesystem to one other.<br>
* <br>
* This file is part of LaTeXDraw<br>
* Copyright (c) 2005-2009 Arnaud BLOUIN<br>
*<br>
* LaTeXDraw is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.<br>
*<br>
* LaTeXDraw is distributed without any warranty; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.<br>
* <br>
* 09/22/09<br>
* @author Arnaud BLOUIN<br>
* @version 2.0.5<br>
*/
public class LFileUtils {
/**
* Copies a file.
* The renameTo method does not allow action across NFS mounted filesystems
* this method is the workaround
* @param fromFile The existing File
* @param toFile The new File
* @return <code>true</code> if and only if the renaming succeeded;
* <code>false</code> otherwise
*/
public final static boolean copy(File fromFile, File toFile) {
if(fromFile==null || toFile==null)
return false;
try {
FileInputStream in = new FileInputStream(fromFile);
FileOutputStream out = new FileOutputStream(toFile);
BufferedInputStream inBuffer = new BufferedInputStream(in);
BufferedOutputStream outBuffer = new BufferedOutputStream(out);
int theByte = 0;
while ((theByte = inBuffer.read()) > -1) {
outBuffer.write(theByte);
}
outBuffer.close();
inBuffer.close();
out.close();
in.close();
// cleanup if files are not the same length
if(fromFile.length() != toFile.length()) {
toFile.delete();
return false;
}
return true;
}
catch(IOException e) { return false; }
}
/**
* Moves a file.
* The renameTo method does not allow action across NFS mounted filesystems
* this method is the workaround
* @param fromFile The existing File
* @param toFile The new File
* @return <code>true</code> if and only if the renaming succeeded;
* <code>false</code> otherwise
*/
public final static boolean move(File fromFile, File toFile) {
if(fromFile==null || toFile==null)
return false;
if(fromFile.renameTo(toFile))
return true;
// delete if copy was successful, otherwise move will fail
if(copy(fromFile, toFile))
return fromFile.delete();
return false;
}
}
|