Skip to content

Commit 9e4243b

Browse files
matthijskooijmancmaglie
authored andcommitted
Add FileUtils.splitFilename()
This allows splitting a filename into a basename and extension. `FileUtils.hasExtension()` is updated to use it, in favour of the String.split-based approached it used before.
1 parent 232f434 commit 9e4243b

File tree

1 file changed

+34
-5
lines changed

1 file changed

+34
-5
lines changed

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

+34-5
Original file line numberDiff line numberDiff line change
@@ -241,15 +241,44 @@ public static boolean hasExtension(File file, String... extensions) {
241241
}
242242

243243
public static boolean hasExtension(File file, List<String> extensions) {
244-
String pieces[] = file.getName().split("\\.");
245-
if (pieces.length < 2) {
246-
return false;
244+
String extension = splitFilename(file).extension;
245+
return extensions.contains(extension.toLowerCase());
246+
}
247+
248+
/**
249+
* The result of a splitFilename call.
250+
*/
251+
public static class SplitFile {
252+
public SplitFile(String basename, String extension) {
253+
this.basename = basename;
254+
this.extension = extension;
247255
}
248256

249-
String extension = pieces[pieces.length - 1];
257+
public String basename;
258+
public String extension;
259+
}
250260

251-
return extensions.contains(extension.toLowerCase());
261+
/**
262+
* Splits the given filename into a basename (everything up to the
263+
* last dot) and an extension (everything from the last dot). The dot
264+
* is not included in either part.
265+
*
266+
* If no dot is present, the entire filename is returned as the
267+
* basename, leaving the extension empty (empty string, not null).
268+
*/
269+
public static SplitFile splitFilename(String filename) {
270+
int index = filename.lastIndexOf(".");
252271

272+
if (index >= 0)
273+
return new SplitFile(filename.substring(0, index), filename.substring(index + 1));
274+
return new SplitFile(filename, "");
275+
}
276+
277+
/**
278+
* Helper function returning splitFilename(file.getName()).
279+
*/
280+
public static SplitFile splitFilename(File file) {
281+
return splitFilename(file.getName());
253282
}
254283

255284
/**

0 commit comments

Comments
 (0)