Skip to content

Commit 84a0d90

Browse files
committed
+= isLegalFile(CharSequence)
1 parent dcf6e82 commit 84a0d90

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

src/main/java/org/apache/commons/io/FileSystem.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ private boolean isIllegalFileNameChar(final char c) {
199199
/**
200200
* Converts a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} to a legal file
201201
* name. Illegal characters in the candidate name are replaced by the {@code replacement} character. If the file
202-
* name exceeds {@link #getMaxFileNameLength()}, then the name is truncated to {@link #getMaxFileNameLength()}.
202+
* name length exceeds {@link #getMaxFileNameLength()}, then the name is truncated to {@link #getMaxFileNameLength()}.
203203
*
204204
* @param candidate
205205
* 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) {
225225
}
226226
return changed ? String.valueOf(charArray) : truncated;
227227
}
228+
229+
/**
230+
* Checks if a candidate file name (without a path)
231+
* such as {@code "filename.ext"} or {@code "filename"}
232+
* is a potentially legal file name.
233+
* If the file name length exceeds {@link #getMaxFileNameLength()},
234+
* or if it contains an illegal character then the check fails.
235+
*
236+
* @param candidate
237+
* a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}
238+
* @return {@code true} if the candidate name is legal
239+
*/
240+
public boolean isLegalFileName(final CharSequence candidate) {
241+
if (candidate == null || candidate.length() == 0 || candidate.length() > maxFileNameLength) {
242+
return false;
243+
}
244+
for (int i = 0; i < candidate.length(); i++) {
245+
if (isIllegalFileNameChar(candidate.charAt(i))) {
246+
return false;
247+
}
248+
}
249+
return true;
250+
}
228251
}

src/test/java/org/apache/commons/io/FileSystemTestCase.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,5 +52,15 @@ public void testToLegalFileNameWindows() {
5252
for (char i = '0'; i < '9'; i++) {
5353
Assert.assertEquals(i, fs.toLegalFileName(String.valueOf(i), replacement).charAt(0));
5454
}
55+
}
56+
57+
@Test
58+
public void testIsLegalName() {
59+
for (FileSystem fs : FileSystem.values()) {
60+
Assert.assertFalse(fs.name(), fs.isLegalFileName("")); // Empty is always illegal
61+
Assert.assertFalse(fs.name(), fs.isLegalFileName(null)); // null is always illegal
62+
Assert.assertFalse(fs.name(), fs.isLegalFileName("\0")); // Assume NUL is always illegal
63+
Assert.assertTrue(fs.name(), fs.isLegalFileName("0")); // Assume simple name always legal
64+
}
5565
}
5666
}

0 commit comments

Comments
 (0)