I\'m making a cross-platform application that renames files based on data retrieved online. I\'d like to sanitize the Strings I took from a web API for the current platform.
Paths.get(...)
throws a detailed exception with the position of the illegal character.
public static String removeInvalidChars(final String fileName)
{
try
{
Paths.get(fileName);
return fileName;
}
catch (final InvalidPathException e)
{
if (e.getInput() != null && e.getInput().length() > 0 && e.getIndex() >= 0)
{
final StringBuilder stringBuilder = new StringBuilder(e.getInput());
stringBuilder.deleteCharAt(e.getIndex());
return removeInvalidChars(stringBuilder.toString());
}
throw e;
}
}