View Javadoc

1   /*
2    *
3    * The DbUnit Database Testing Framework
4    * Copyright (C)2002-2008, DbUnit.org
5    *
6    * This library is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public
8    * License as published by the Free Software Foundation; either
9    * version 2.1 of the License, or (at your option) any later version.
10   *
11   * This library is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   * Lesser General Public License for more details.
15   *
16   * You should have received a copy of the GNU Lesser General Public
17   * License along with this library; if not, write to the Free Software
18   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   *
20   */
21  package org.dbunit.util;
22  
23  import java.io.BufferedReader;
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileOutputStream;
27  import java.io.IOException;
28  import java.io.InputStream;
29  import java.io.InputStreamReader;
30  import java.net.MalformedURLException;
31  import java.nio.channels.FileChannel;
32  import java.util.ArrayList;
33  import java.util.List;
34  
35  import org.slf4j.Logger;
36  import org.slf4j.LoggerFactory;
37  import org.xml.sax.InputSource;
38  
39  /**
40   * Utility that provides some general methods for working with {@link File} objects.
41   * 
42   * @author gommma
43   * @version $Revision: 884 $
44   * @since 2.3.0
45   */
46  public class FileHelper
47  {
48  	private static Logger logger = LoggerFactory.getLogger(FileHelper.class);
49  
50  	private FileHelper(){
51  	}
52  	
53  	/**
54       * Recursively deletes the given directory
55       * @param directory The directory to delete
56  	 * @param failOnError If an exception should be thrown in case the deletion did not work.
57  	 */
58  	public static void deleteDirectory(File directory, boolean failOnError) {
59  	    boolean success = deleteDirectory(directory);
60  	    if(!success){
61  	        throw new RuntimeException("Failed to delete directory " + directory);
62  	    }
63  	}
64  
65  	/**
66  	 * Recursively deletes the given directory
67  	 * @param directory The directory to delete
68  	 * @return <code>true</code> if the deletion was successfully.
69  	 */
70  	public static boolean deleteDirectory(File directory)
71  	{
72  		if(!directory.isDirectory()) {
73  			logger.warn("The directory '" + directory + "' does not exist. Will return without delete.");
74  			return false;
75  		}
76  		
77  		// First we must delete all files in the directory
78  		File[] containedFiles = directory.listFiles();
79  		for (int i = 0; i < containedFiles.length; i++) {
80  			File currentFile = containedFiles[i];
81  			if(currentFile.isDirectory()) {
82  				// First delete children recursively
83  				deleteDirectory(currentFile);
84  			}
85  			else {
86  				// Delete the file itself
87  				boolean success = currentFile.delete();
88  				if(!success){
89  					logger.warn("Failed to delete file '" + currentFile + "'");
90  				}
91  			}		
92  		}
93  		// Finally delete the directory itself
94  		boolean success = directory.delete();
95  		if(!success){
96  			logger.warn("Failed to delete file '" + directory + "'");
97  		}
98  		return success;
99  	}
100 
101 	public static InputSource createInputSource(File file) throws MalformedURLException
102 	{
103         String uri = file/*.getAbsoluteFile()*/.toURI().toURL().toString();
104         InputSource source = new InputSource(uri);
105         return source;
106 	}
107 	
108 	
109     /**
110      * Copy file.
111      * 
112      * @param srcFile the src file
113      * @param destFile the dest file
114      * @throws IOException 
115      */
116     public static void copyFile(File srcFile, File destFile) throws IOException 
117     {
118         logger.debug("copyFile(srcFile={}, destFile={}) - start", srcFile, destFile);
119 
120         // Create channel on the source
121         FileChannel srcChannel = new FileInputStream(srcFile).getChannel();
122 
123         // Create channel on the destination
124         FileChannel dstChannel = new FileOutputStream(destFile).getChannel();
125 
126         try {
127             // Copy file contents from source to destination
128             dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
129         }
130         finally {
131             // Close the channels
132             srcChannel.close();
133             dstChannel.close();
134         }
135     }
136 
137     /**
138      * Get a list of Strings from a given file.
139      * Uses the default encoding of the current platform.
140      * 
141      * @param theFile the file to be read
142      * @return a list of Strings, each one representing one line from the given file
143      * @throws IOException
144      */
145     public static List readLines(File theFile) throws IOException 
146     {
147         logger.debug("readLines(theFile={}) - start", theFile);
148 
149         InputStream tableListStream = new FileInputStream(theFile);
150         try {
151             List orderedNames = new ArrayList();
152             BufferedReader reader = new BufferedReader(new InputStreamReader(tableListStream));
153             String line = null;
154             while ((line = reader.readLine()) != null) {
155                 String table = line.trim();
156                 if (table.length() > 0) {
157                     orderedNames.add(table);
158                 }
159             }
160             return orderedNames;
161         }
162         finally {
163             tableListStream.close();
164         }
165     }
166 
167 }