View Javadoc

1   /*
2    * Copyright 2006-2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.springframework.osgi.test.internal.util;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.io.OutputStream;
22  
23  /**
24   * Utility class for IO operations.
25   * 
26   * @author Costin Leau
27   * 
28   */
29  public abstract class IOUtils {
30  
31  	public static interface IOCallback {
32  		void doWithIO() throws IOException;
33  	}
34  
35  	public static void doWithIO(IOCallback callback) {
36  		try {
37  			callback.doWithIO();
38  		}
39  		catch (IOException ioException) {
40  
41  		}
42  	}
43  
44  	public static void closeStream(InputStream stream) {
45  		if (stream != null)
46  			try {
47  				stream.close();
48  			}
49  			catch (IOException ex) {
50  				// ignore
51  			}
52  	}
53  
54  	public static void closeStream(OutputStream stream) {
55  		if (stream != null)
56  			try {
57  				stream.close();
58  			}
59  			catch (IOException ex) {
60  				// ignore
61  			}
62  	}
63  
64  	/**
65  	 * Delete the given file (can be a simple file or a folder).
66  	 * 
67  	 * @param file the file to be deleted
68  	 * @return if the deletion succeded or not
69  	 */
70  	public static boolean delete(File file) {
71  
72  		// bail out quickly
73  		if (file == null)
74  			return false;
75  
76  		// recursively delete children file
77  		boolean success = true;
78  
79  		if (file.isDirectory()) {
80  			String[] children = file.list();
81  			for (int i = 0; i < children.length; i++) {
82  				success &= delete(new File(file, children[i]));
83  			}
84  		}
85  
86  		// The directory is now empty so delete it
87  		return (success &= file.delete());
88  	}
89  }