Reputation: 933
How to remove invalid characters from a String , so that it can be used as a file name ?
the invalid characters include ("\\/:*?\"<>|")
.
Upvotes: 31
Views: 34994
Reputation: 59303
You can replace characters by replaceAll()
:
@Test
public void testName() throws Exception
{
assertEquals("", "\\/:*?\"<>|".replaceAll("[\\\\/:*?\"<>|]", ""));
}
however, note that
.
(current directory) and ..
(parent directory) on its own are also invalid, although you allow dots&
is also a disallowed character (might be Microsoft specific)COM1
is also an invalid file name, although it has legal characters only (also applies to PRN
, LPT1
and similar) (might be Microsoft specific)$MFT
and similar are also invalid, although you can use $
in general (might be NTFS specific)Upvotes: 2
Reputation: 2081
You can use regex
String s= string.replaceAll("[\\\\/:*?\"<>|]", "");
Upvotes: 3
Reputation: 22972
You can try this,
String fileName = "\\/:*AAAAA?\"<>|3*7.pdf";
String invalidCharRemoved = fileName.replaceAll("[\\\\/:*?\"<>|]", "");
System.out.println(invalidCharRemoved);
OUTPUT
AAAAA37.pdf
Upvotes: 44
Reputation: 3200
You should not try to second guess the user. If the provided filename is incorrect just show an error message or throw an exception as appropriate.
Removing those invalid characters from a suplied filename does in no way ensure that the new filename is valid.
Upvotes: 3