Is there a cross-platform Java method to remove filename special chars?

后端 未结 8 1605
太阳男子
太阳男子 2021-01-31 13:26

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.

8条回答
  •  故里飘歌
    2021-01-31 14:09

    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;
      }
    }
    

提交回复
热议问题