curious
curious

Reputation: 933

removing invalid characters (("\\/:*?\"<>|") ) from a string to use it as a FileName

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

Answers (4)

Thomas Weller
Thomas Weller

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
  • for using the file with WebDAV, & 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

Sanjay Rabari
Sanjay Rabari

Reputation: 2081

You can use regex

 String s= string.replaceAll("[\\\\/:*?\"<>|]", "");

Upvotes: 3

Akash Thakare
Akash Thakare

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

Anonymous Coward
Anonymous Coward

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

Related Questions