Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing illegal character in fileName

In Java, I've a File-Name-String. There I want to replace all illegal Characters with '_', but not a-z, 0-9, -,. and _

I tried following code: But this did not worked!

myString = myString.replaceAll("[\\W][^\\.][^-][^_]", "_"); 
like image 911
bbholzbb Avatar asked Feb 25 '13 20:02

bbholzbb


People also ask

How do you fix illegal characters in path?

You can simply use C# inbuilt function " Path. GetInvalidFileNameChars() " to check if there is invalid character in file name and remove it. var InvalidCharacters= Path. GetInvalidFileNameChars(); string GetInvalidCharactersRemovedString= new string(fileName .

What characters are illegal path?

The "Illegal characters" exception means that the file path string you are passing to ReadXml is wrong: it is not a valid path. It may contain '?' , or ':' in the wrong place, or '*' for example. You need to look at the value, check what it is, and work out where the illegal character(s) are coming from.

What is an illegal character?

illegal character Any character not in the character set of a given machine or not allowed by a given programming language or protocol. A Dictionary of Computing.


2 Answers

You need to replace everything but [a-zA-Z0-9.-]. The ^ within the brackets stands for "NOT".

myString = myString.replaceAll("[^a-zA-Z0-9\\.\\-]", "_"); 
like image 144
poitroae Avatar answered Sep 23 '22 20:09

poitroae


If you are looking for options on windows platform then you can try below solution to make use of all valid characters other than "\/:*?"<>|" in file name.

fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_"); 
like image 40
Prakash Avatar answered Sep 22 '22 20:09

Prakash