1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.any23.util;
19
20 import java.io.BufferedInputStream;
21 import java.io.BufferedOutputStream;
22 import java.io.ByteArrayOutputStream;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.FileOutputStream;
27 import java.io.FileWriter;
28 import java.io.FilenameFilter;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.PrintWriter;
32 import java.util.ArrayList;
33 import java.util.List;
34
35 /**
36 * Utility class for handling files.
37 *
38 * @author Michele Mostarda (mostarda@fbk.eu)
39 */
40 public class FileUtils {
41
42 /**
43 * Moves a <code>target</code> file to a new <code>dest</code> location.
44 *
45 * @param target file to be moved.
46 * @param dest dest dir.
47 * @return destination file.
48 */
49 public static File mv(File target, File dest) {
50 if (!dest.isDirectory()) {
51 throw new IllegalArgumentException("destination must be a directory.");
52 }
53
54 final File newFile = new File(dest, target.getName());
55 boolean success = target.renameTo(newFile);
56 if (!success) {
57 throw new IllegalStateException(
58 String.format("Cannot move target file [%s] to destination [%s]", target, newFile)
59 );
60 }
61 return newFile;
62 }
63
64 /**
65 * Copies the content of the input stream within the given dest file.
66 * The dest file must not exist.
67 *
68 * @param is
69 * @param dest
70 */
71 public static void cp(InputStream is, File dest) {
72 if (dest.exists()) {
73 throw new IllegalArgumentException("Destination must not exist.");
74 }
75 BufferedInputStream bis = null;
76 BufferedOutputStream bos = null;
77 try {
78 bis = new BufferedInputStream(is);
79 FileOutputStream fos = new FileOutputStream(dest);
80 bos = new BufferedOutputStream(fos);
81 final byte[] buffer = new byte[1024 * 4];
82 int read;
83 while (true) {
84 read = bis.read(buffer);
85 if (read == -1) {
86 break;
87 }
88 bos.write(buffer, 0, read);
89 }
90 } catch (Exception e) {
91 throw new RuntimeException("Error while copying stream into file.", e);
92 } finally {
93 StreamUtils.closeGracefully(bis);
94 StreamUtils.closeGracefully(bos);
95 }
96 }
97
98 /**
99 * Copies a file <code>src</code> to the <code>dest</code>.
100 *
101 * @param src source file.
102 * @param dest destination file.
103 * @throws java.io.FileNotFoundException if file cannot be copied or created.
104 */
105 public static void cp(File src, File dest) throws FileNotFoundException {
106 FileInputStream fis = null;
107 try {
108 fis = new FileInputStream(src);
109 cp(fis, dest);
110 } finally {
111 StreamUtils.closeGracefully(fis);
112 }
113 }
114
115 /**
116 * Dumps the given string within a file.
117 *
118 * @param f file target.
119 * @param content content to be dumped.
120 * @throws IOException
121 */
122 public static void dumpContent(File f, String content) throws IOException {
123 FileWriter fw = new FileWriter(f);
124 try {
125 fw.write(content);
126 } finally {
127 StreamUtils.closeGracefully(fw);
128 }
129 }
130
131 /**
132 * Dumps the stack trace of the given exception into the specified file.
133 *
134 * @param f file to generate dump.
135 * @param t exception to be dumped.
136 * @throws IOException
137 */
138 public static void dumpContent(File f, Throwable t) throws IOException {
139 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
140 final PrintWriter pw = new PrintWriter(baos);
141 t.printStackTrace(pw);
142 pw.close();
143 dumpContent(f, baos.toString());
144 }
145
146 /**
147 * Reads a resource file and returns the content as a string.
148 *
149 * @param clazz the class to use load the resource.
150 * @param resource the resource to be load.
151 * @return the string representing the file content.
152 * @throws java.io.IOException
153 */
154 public static String readResourceContent(Class clazz, String resource) throws IOException {
155 return StreamUtils.asString( clazz.getResourceAsStream(resource) );
156 }
157
158 /**
159 * Reads a resource file and returns the content as a string.
160 *
161 * @param resource the resource to be load.
162 * @return the string representing the file content.
163 * @throws java.io.IOException
164 */
165 public static String readResourceContent(String resource) throws IOException {
166 return readResourceContent(FileUtils.class, resource);
167 }
168
169 /**
170 * Returns the content of a file a single string.
171 *
172 * @param f the file to read.
173 * @return the content of file.
174 * @throws IOException if an error occurs while locating or accessing the file.
175 */
176 public static String readFileContent(File f) throws IOException {
177 FileInputStream fis = new FileInputStream(f);
178 return StreamUtils.asString(fis, true);
179 }
180
181 /**
182 * Returns all the lines of a file.
183 *
184 * @param f the file to read.
185 * @return a not <code>null</code> array with not <code>null</code> line strings.
186 * @throws IOException if an error occurs while locating or accessing the file.
187 */
188 public static String[] readFileLines(File f) throws IOException {
189 FileInputStream fis = new FileInputStream(f);
190 return StreamUtils.asLines(fis);
191 }
192
193 /**
194 * Lists the content of a dir applying the specified filter.
195 *
196 * @param dir directory root.
197 * @param filenameFilter filter to be applied.
198 * @return list of matching files.
199 */
200 public static File[] listFilesRecursively(File dir, FilenameFilter filenameFilter) {
201 if( ! dir.isDirectory() ) {
202 throw new IllegalArgumentException(dir.getAbsolutePath() + " must be a directory.");
203 }
204 final List<File> result = new ArrayList<File>();
205 visitFilesRecursively(dir, filenameFilter, result);
206 return result.toArray( new File[result.size()] );
207 }
208
209 /**
210 * Visits a directory recursively, applying the given filter and adding matches to the result list.
211 *
212 * @param dir directory to find.
213 * @param filenameFilter filter to apply.
214 * @param result result list.
215 */
216 private static void visitFilesRecursively(File dir, FilenameFilter filenameFilter, List<File> result) {
217 for (File file : dir.listFiles()) {
218 if (!file.isDirectory()) {
219 if (filenameFilter == null || filenameFilter.accept(dir, file.getName())) {
220 result.add(file);
221 }
222 } else {
223 visitFilesRecursively(file, filenameFilter, result);
224 }
225 }
226 }
227
228 /**
229 * Function class.
230 */
231 private FileUtils() {}
232
233 }