Debian Codegraph @

arduino-core/src/processing/app/helpers/FileUtils.java

raw symbols SCIP
1 package processing.app.helpers;
2
3 import org.apache.commons.compress.utils.IOUtils;
4
5 import java.io.BufferedReader;
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStreamReader;
11 import java.io.OutputStream;
12 import java.nio.charset.Charset;
13 import java.nio.charset.StandardCharsets;
14 import java.nio.file.Files;
15 import java.nio.file.Paths;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.List;
19 import java.util.Random;
20
21 public class FileUtils {
22
23 private static final List<String> SOURCE_CONTROL_FOLDERS = Arrays.asList("CVS", "RCS", ".git", ".svn", ".hg", ".bzr");
24
25 /**
26 * Checks, whether the child directory is a subdirectory of the base directory.
27 *
28 * @param base the base directory.
29 * @param child the suspected child directory.
30 * @return true, if the child is a subdirectory of the base directory.
31 */
32 public static boolean isSubDirectory(File base, File child) {
33 try {
34 base = base.getCanonicalFile();
35 child = child.getCanonicalFile();
36 } catch (IOException e) {
37 return false;
38 }
39
40 File parentFile = child;
41 while (parentFile != null) {
42 if (base.equals(parentFile)) {
43 return true;
44 }
45 parentFile = parentFile.getParentFile();
46 }
47 return false;
48 }
49
50 public static void copyFile(File source, File dest) throws IOException {
51 FileInputStream fis = null;
52 FileOutputStream fos = null;
53 try {
54 fis = new FileInputStream(source);
55 fos = new FileOutputStream(dest);
56 byte[] buf = new byte[4096];
57 int readBytes = -1;
58 while ((readBytes = fis.read(buf, 0, buf.length)) != -1) {
59 fos.write(buf, 0, readBytes);
60 }
61 } finally {
62 IOUtils.closeQuietly(fis);
63 IOUtils.closeQuietly(fos);
64 }
65 }
66
67 public static void copy(File sourceFolder, File destFolder) throws IOException {
68 for (File file : sourceFolder.listFiles()) {
69 File destFile = new File(destFolder, file.getName());
70 if (file.isDirectory() && !SOURCE_CONTROL_FOLDERS.contains(file.getName())) {
71 if (!destFile.exists() && !destFile.mkdir()) {
72 throw new IOException("Unable to create folder: " + destFile);
73 }
74 copy(file, destFile);
75 } else if (!file.isDirectory()) {
76 copyFile(file, destFile);
77 }
78 }
79 }
80
81 public static void recursiveDelete(File file) {
82 if (file == null) {
83 return;
84 }
85 if (file.isDirectory()) {
86 File[] files = file.listFiles();
87 if (files == null) {
88 return;
89 }
90 for (File current : files) {
91 recursiveDelete(current);
92 }
93 }
94 file.delete();
95 }
96
97 public static File createTempFolder() throws IOException {
98 return createTempFolder(new File(System.getProperty("java.io.tmpdir")));
99 }
100
101 public static File createTempFolder(File parent) throws IOException {
102 return createTempFolder(parent, "arduino_");
103 }
104
105 public static File createTempFolder(File parent, String prefix) throws IOException {
106 return createTempFolder(parent, prefix, Integer.toString(new Random().nextInt(1000000)));
107 }
108
109 public static File createTempFolder(String prefix) throws IOException {
110 return createTempFolder(new File(System.getProperty("java.io.tmpdir")), prefix);
111 }
112
113 public static File createTempFolder(String prefix, String suffix) throws IOException {
114 return createTempFolder(new File(System.getProperty("java.io.tmpdir")), prefix, suffix);
115 }
116
117 public static File createTempFolder(File parent, String prefix, String suffix) throws IOException {
118 return Files.createDirectories(Paths.get(parent.getAbsolutePath(), prefix + suffix)).toFile();
119 }
120
121 public static boolean isSCCSOrHiddenFile(File file) {
122 return isSCCSFolder(file) || isHiddenFile(file);
123 }
124
125 public static boolean isHiddenFile(File file) {
126 return file.isHidden() || file.getName().charAt(0) == '.';
127 }
128
129 public static boolean isSCCSFolder(File file) {
130 return file.isDirectory() && SOURCE_CONTROL_FOLDERS.contains(file.getName());
131 }
132
133 public static String readFileToString(File file) throws IOException {
134 return readFileToString(file, "UTF-8");
135 }
136
137 public static String readFileToString(File file, String encoding) throws IOException {
138 BufferedReader reader = null;
139 try {
140 reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
141 StringBuilder sb = new StringBuilder();
142 String line;
143 while ((line = reader.readLine()) != null) {
144 sb.append(line).append("\n");
145 }
146 return sb.toString();
147 } finally {
148 IOUtils.closeQuietly(reader);
149 }
150 }
151
152 /**
153 * Writes the given data to the given file, creating the file if it does not exist.
154 * This method is equivalent to calling {@code writeStringToFile(file, data, StandardCharsets.UTF_8)}.
155 * @param file - The file to write to.
156 * @param data - The string to write.
157 * @throws IOException If an I/O error occurs.
158 */
159 public static void writeStringToFile(File file, String data) throws IOException {
160 writeStringToFile(file, data, StandardCharsets.UTF_8);
161 }
162
163 /**
164 * Writes the given data to the given file, creating the file if it does not exist.
165 * @param file - The file to write to.
166 * @param data - The string to write.
167 * @param charset - The charset used to convert the string to bytes.
168 * @throws IOException If an I/O error occurs.
169 */
170 public static void writeStringToFile(File file, String data, Charset charset) throws IOException {
171 OutputStream out = null;
172 try {
173 out = new FileOutputStream(file);
174 out.write(data.getBytes(charset));
175 } finally {
176 IOUtils.closeQuietly(out);
177 }
178 }
179
180 /**
181 * Returns true if the given file has any of the given extensions.
182 *
183 * @param file File whose name to look at
184 * @param extensions Extensions to consider (just the extension, without the
185 * dot). Should all be lowercase, case insensitive matching
186 * is used.
187 */
188 public static boolean hasExtension(File file, List<String> extensions) {
189 String extension = splitFilename(file).extension;
190 return extensions.contains(extension.toLowerCase());
191 }
192
193 /**
194 * Returns the given filename with the extension replaced by the one
195 * given. If the filename does not have an extension yet, one is
196 * added.
197 */
198 public static String replaceExtension(String filename, String extension) {
199 SplitFile split = splitFilename(filename);
200 split.extension = extension;
201 return split.join();
202 }
203
204 /**
205 * Returns the given filename with the extension replaced by the one
206 * given. If the filename does not have an extension yet, one is
207 * added.
208 */
209 public static File replaceExtension(File file, String extension) {
210 return new File(file.getParentFile(), replaceExtension(file.getName(), extension));
211 }
212
213 /**
214 * Adds an extension to the given filename. If it already contains
215 * one, an additional extension is added. If the extension is the
216 * empty string, the file is returned unmodified.
217 */
218 public static String addExtension(String filename, String extension) {
219 return extension.equals("") ? filename : (filename + "." + extension);
220 }
221
222 /**
223 * Adds an extension to the given filename. If it already contains
224 * one, an additional extension is added. If the extension is the
225 * empty string, the file is returned unmodified.
226 */
227 public static File addExtension(File file, String extension) {
228 return new File(file.getParentFile(), addExtension(file.getName(), extension));
229 }
230
231 /**
232 * The result of a splitFilename call.
233 */
234 public static class SplitFile {
235 public SplitFile(String basename, String extension) {
236 this.basename = basename;
237 this.extension = extension;
238 }
239
240 public String basename;
241 public String extension;
242
243 public String join() {
244 return addExtension(basename, extension);
245 }
246 }
247
248 /**
249 * Splits the given filename into a basename (everything up to the
250 * last dot) and an extension (everything from the last dot). The dot
251 * is not included in either part.
252 *
253 * If no dot is present, the entire filename is returned as the
254 * basename, leaving the extension empty (empty string, not null).
255 */
256 public static SplitFile splitFilename(String filename) {
257 int index = filename.lastIndexOf(".");
258
259 if (index >= 0)
260 return new SplitFile(filename.substring(0, index), filename.substring(index + 1));
261 return new SplitFile(filename, "");
262 }
263
264 /**
265 * Helper function returning splitFilename(file.getName()).
266 */
267 public static SplitFile splitFilename(File file) {
268 return splitFilename(file.getName());
269 }
270
271 /**
272 * Recursively find all files in a folder with the specified
273 * extension. Excludes hidden files and folders and
274 * source control folders.
275 *
276 * @param folder Folder to look into
277 * @param recursive <b>true</b> will recursively find all files in sub-folders
278 * @param extensions A list of file extensions to search (just the extension,
279 * without the dot). Should all be lowercase, case
280 * insensitive matching is used. If no extensions are
281 * passed, all files are returned.
282 * @return
283 */
284 public static List<File> listFiles(File folder, boolean recursive,
285 String... extensions) {
286 return listFiles(folder, recursive, Arrays.asList(extensions));
287 }
288
289 public static List<File> listFiles(File folder, boolean recursive,
290 List<String> extensions) {
291 List<File> result = new ArrayList<>();
292 if (!folder.exists()) {
293 return result;
294 }
295
296 for (File file : folder.listFiles()) {
297 if (isSCCSOrHiddenFile(file))
298 continue;
299
300 if (file.isDirectory()) {
301 if (recursive)
302 result.addAll(listFiles(file, true, extensions));
303 continue;
304 }
305
306 if (extensions.isEmpty() || hasExtension(file, extensions))
307 result.add(file);
308 }
309 return result;
310 }
311
312 }