//---------------------------------------------------------------------- // // $Author: AJR $ // $Date: 2006-02-03 15:03:59 $ // $Revision: 1.2 $ // $Source: /CVS/java/javaLib/src/at/anzac/util/FileUtil.java,v $ // // Copyright (C) 2006 Andreas J. Resch // // This program 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. // // This program is distributed in the hope that it will be useful, but 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. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110, USA //---------------------------------------------------------------------- package at.anzac.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.logging.Level; import java.util.logging.Logger; /********************************************************************************** * FileUtil is a collection of utility functions that handle files. * {@link #_levelDebug}, {@link #_levelWarning} and {@link #_levelError} define * the levels used for logging. *********************************************************************************/ public class FileUtil { /** log level for errors */ public static Level _levelError=Level.SEVERE; /** log level for warning (e.g. failure on file close) */ public static Level _levelWarning=Level.WARNING; /** log level for debugging */ public static Level _levelDebug=Level.FINER; /********************************************************************************** * copy a file to another name. * @param src file to be copied * @param dest name of the destination file * @param log logger to use for logging - may be null for no logging * @throws Exception *********************************************************************************/ public static void copy(String src,String dest,Logger log) throws Exception { copy(src,dest,false,log); } /********************************************************************************** * copy a file to another name. * @param src file to be copied * @param dest name of the destination file * @param append true to append to the destination file, false to overwrite it * @param log logger to use for logging - may be null for no logging * @throws Exception *********************************************************************************/ public static void copy(String src,String dest,boolean append,Logger log) throws Exception { int n; byte buff[]; FileInputStream reader; FileOutputStream writer; buff=new byte[32768]; reader=null; writer=null; try { reader=new FileInputStream(src); writer=new FileOutputStream(dest,append); while(reader.available()>0) { n=reader.read(buff); writer.write(buff,0,n); } writer.flush(); writer.close(); reader.close(); } catch(Exception e) { close(reader,log); close(writer,log); delete(dest,log); throw e; } } /********************************************************************************** * move a file to another name. * @param src file to move * @param dest destination file * @param log logger to use for logging - may be null for no logging * @throws Exception *********************************************************************************/ public static void move(String src,String dest,Logger log) throws Exception { File srcFile,dstFile; try // try rename { srcFile=new File(src); dstFile=new File(dest); if(log!=null) { if(log.isLoggable(_levelDebug)) { log.log(_levelDebug,"moving file '"+srcFile.getCanonicalPath()+"' to '"+dstFile.getCanonicalPath()+"'."); } } if(!srcFile.renameTo(dstFile)) { throw new Exception(); } } catch(Exception e) // rename failed -> try copy and delete { if(log!=null) { log.log(_levelDebug,"rename failed - trying copy&delete."); } copy(src,dest,log); if(!delete(src,log)) { delete(dest,log); throw new Exception("error deleteing source file '"+src+"'"); } } } /********************************************************************************** * delete a file. * @param name file that shall be deleted * @param log logger to use for logging - may be null for no logging * @return true if the deletion was successful, otherwise false; *********************************************************************************/ public static boolean delete(String name,Logger log) { return delete(new File(name),log); } /********************************************************************************** * delete a file. * @param file file that shall be deleted * @param log logger to use for logging - may be null for no logging * @return true if the deletion was successful, otherwise false; *********************************************************************************/ public static boolean delete(File file,Logger log) { try { if(file==null) { if(log!=null) { log.log(_levelDebug,"file is null."); } return false; } if(!file.isFile()) { if(log!=null) { log.log(_levelError,"cannot delete '"+file.getCanonicalPath()+"' - it's not a file."); } return false; } if(log!=null) { if(log.isLoggable(_levelDebug)) { log.log(_levelDebug,"deleteing file '"+file.getCanonicalPath()+"'."); } } return file.delete(); } catch(Exception e) { if(log!=null) { log.log(_levelError,"error deleteing file",e); } return false; } } /********************************************************************************** * close a reader * if an exception occurs it is catched and false ia returned. * @param reader reader to close * @param log logger to use for logging - may be null for no logging * @return true on success, otherwise false *********************************************************************************/ public static boolean close(Reader reader,Logger log) { try { if(reader==null) { if(log!=null) { log.log(_levelDebug,"reader is null."); } return false; } reader.close(); return true; } catch(Exception e) { if(log!=null) { log.log(_levelWarning,"error closeing",e); } return false; } } /********************************************************************************** * flush and close a writer * if an exception occurs it is catched and false ia returned. * @param writer writer to close * @param log logger to use for logging - may be null for no logging * @return true on success, otherwise false *********************************************************************************/ public static boolean close(Writer writer,Logger log) { try { if(writer==null) { if(log!=null) { log.log(_levelDebug,"writer is null."); } return false; } writer.flush(); writer.close(); return true; } catch(Exception e) { if(log!=null) { log.log(_levelWarning,"error closeing",e); } return false; } } /********************************************************************************** * close an input stream. * if an exception occurs it is catched and false ia returned. * @param is stream to close * @param log logger to use for logging - may be null for no logging * @return true on success, otherwise false *********************************************************************************/ public static boolean close(InputStream is,Logger log) { try { if(is==null) { if(log!=null) { log.log(_levelDebug,"inputstream is null."); } return false; } is.close(); return true; } catch(Exception e) { if(log!=null) { log.log(_levelWarning,"error closeing",e); } return false; } } /********************************************************************************** * flush and close an output stream. * if an exception occurs it is catched and false ia returned. * @param os stream to close * @param log logger to use for logging - may be null for no logging * @return true on success, otherwise false *********************************************************************************/ public static boolean close(OutputStream os,Logger log) { try { if(os==null) { if(log!=null) { log.log(_levelDebug,"outputstream is null."); } return false; } os.flush(); os.close(); return true; } catch(Exception e) { if(log!=null) { log.log(_levelWarning,"error closeing",e); } return false; } } /********************************************************************************** * return the name without path and without extension. * @param file filename to get the name from * @return the name without path and without extension or an empty string *********************************************************************************/ public static String getNameWithoutExtension(String file) { try { return getNameWithoutExtension(new File(file)); } catch(Exception e) { return ""; } } /********************************************************************************** * return the name without path and without extension. * @param file file to get the name from * @return the name without path and without extension or an empty string *********************************************************************************/ public static String getNameWithoutExtension(File file) { int idx; String name; try { name=file.getName(); idx=name.indexOf('.'); if(idx>0) { return name.substring(0,idx); } return name; } catch(Exception e) { return ""; } } /********************************************************************************** * read a line from a buffered input stream. * @param bis {@link BufferedInputStream} to read from * @return the next line without CR/LF * @throws Exception *********************************************************************************/ public static String readLine(BufferedInputStream bis) throws Exception { int c; StringBuffer buff; buff=new StringBuffer(); while(bis.available()>0) { c=bis.read(); // CR read if(c==13) { // check for LF in next char if(bis.available()>0) { bis.mark(1); c=bis.read(); if(c!=10) // next char is not a LF { bis.reset(); } } } // LF read if(c==10) { break; } buff.append((char)c); } return buff.toString(); } /********************************************************************************** * add text to a file * writes some text to a file. * @param text text to write to the file * @param dest name of the destination file * @param append true to append to the destination file, false to overwrite it * @param log logger to use for logging - may be null for no logging * @throws Exception *********************************************************************************/ public static void addText(String text,String dest,boolean append,Logger log) throws Exception { FileOutputStream writer; writer=null; try { writer=new FileOutputStream(dest,append); writer.write(text.getBytes()); writer.flush(); writer.close(); } catch(Exception e) { close(writer,log); delete(dest,log); throw e; } } /*********************************************************************************** * checks if dir exist otherwise creates dir. * @param name path of the directory to create/check * @throws Exception * @return the directory path with trailing slash/backslash *********************************************************************************/ public static String createAndCheckDir(String name) throws Exception { File dir; String path; dir=new File(name); path=dir.getCanonicalPath(); // check if the path is a valid one if(!dir.exists()) // create the dir if it does not exist { dir.mkdirs(); if(!dir.exists()) // creation of dir failed -> fallback { throw new Exception("error creating directory '"+dir.getCanonicalPath()+"'"); } } if(!path.endsWith(File.separator)) // add trailing slash/backslash { path=path+File.separator; } return path; } /******************************************************************************** * delete all or only old files in a directory. * @param name fully qulaifed name of the directory * @param maxDays maximum age of a file in days * @param onlyOld true to delete only old files, false to delete all files * @param log logger to use for logging - may be null for no logging * @return true if the operation ended without any error, false if an error occured *********************************************************************************/ public static boolean clearDirectory(String name,int maxDays,boolean onlyOld,Logger log) { int i; long max,now; File dir,file; String names[]; boolean ok; dir=new File(name); names=dir.list(); max=maxDays*86400000; // 86400000 -> one day in ms now=System.currentTimeMillis(); ok=true; for(i=0;imax)||(!onlyOld)) { FileUtil.delete(file,log); } } } catch(Exception e) { ok=false; } } return ok; } } //---------------------------------------------------------------------- // // $Log: FileUtil.java,v $ // Revision 1.2 2006-02-03 15:03:59 AJR // added GPL statement. // // Revision 1.1 2006/01/20 17:51:35 AJR // imported from jars java lib. // // //----------------------------------------------------------------------