+= isLegalFile(CharSequence)
MODIFY
src/main/java/org/apache/commons/io/FileSystem.java
src/main/java/org/apache/commons/io/FileSystem.java
@@ -199,7 +199,7 @@ private boolean isIllegalFileNameChar(final char c) {
/**
* Converts a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} to a legal file
* name. Illegal characters in the candidate name are replaced by the {@code replacement} character. If the file
- * name exceeds {@link #getMaxFileNameLength()}, then the name is truncated to {@link #getMaxFileNameLength()}.
+ * name length exceeds {@link #getMaxFileNameLength()}, then the name is truncated to {@link #getMaxFileNameLength()}.
*
* @param candidate
* a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
@@ -225,4 +225,27 @@ public String toLegalFileName(final String candidate, final char replacement) {
}
return changed ? String.valueOf(charArray) : truncated;
}
+
+ /**
+ * Checks if a candidate file name (without a path)
+ * such as {@code "filename.ext"} or {@code "filename"}
+ * is a potentially legal file name.
+ * If the file name length exceeds {@link #getMaxFileNameLength()},
+ * or if it contains an illegal character then the check fails.
+ *
+ * @param candidate
+ * a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
+ * @return {@code true} if the candidate name is legal
+ */
+ public boolean isLegalFileName(final CharSequence candidate) {
+ if (candidate == null || candidate.length() == 0 || candidate.length() > maxFileNameLength) {
+ return false;
+ }
+ for (int i = 0; i < candidate.length(); i++) {
+ if (isIllegalFileNameChar(candidate.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
}
\ No newline at end of file

MODIFY
src/test/java/org/apache/commons/io/FileSystemTestCase.java
src/test/java/org/apache/commons/io/FileSystemTestCase.java
@@ -53,4 +53,14 @@ public void testToLegalFileNameWindows() {
Assert.assertEquals(i, fs.toLegalFileName(String.valueOf(i), replacement).charAt(0));
}
}
+
+ @Test
+ public void testIsLegalName() {
+ for (FileSystem fs : FileSystem.values()) {
+ Assert.assertFalse(fs.name(), fs.isLegalFileName("")); // Empty is always illegal
+ Assert.assertFalse(fs.name(), fs.isLegalFileName(null)); // null is always illegal
+ Assert.assertFalse(fs.name(), fs.isLegalFileName("\0")); // Assume NUL is always illegal
+ Assert.assertTrue(fs.name(), fs.isLegalFileName("0")); // Assume simple name always legal
+ }
+ }
}

+= isLegalFile(CharSequence)