4 Replies Latest reply: May 16, 2009 9:56 AM by 807588 RSS

    File separator problem

    807588
      Hi,

      I want to store some path to files at a properties file.
      There I put a '$' instead of a file separator so I can later decide how to replace this by the os-depending separator.
      I use the method:
      replaceAll( "$", File.separator );
      but this won't work ... a "java.lang.StringIndexOutOfBoundsException: String index out of range: 1" was thrown...
      Any ideas?

      regards,

      Olek
        • 1. Re: File separator problem
          807588
          re,

          I found the error the $ sign is not the best choice for a placeholder ;)

          from the code of java.util.regex.Matcher :
           while (cursor < replacement.length()) {
                      char nextChar = replacement.charAt(cursor);
                      if (nextChar == '\\') {
                          cursor++;
                          nextChar = replacement.charAt(cursor);
                          result.append(nextChar);
                          cursor++;
                      } else if (nextChar == '$') {
                          // Skip past $
          Olek
          • 2. Re: File separator problem
            807588
            re again,

            The best way to handle such strings is to use
            Matcher.quoteReplacement( stringWithDollarOrSlash );
            Olek
            • 3. Re: File separator problem
              807588
              last posting :

              Here is a simple code which does the same but easier :
              public static String getLocalizedPath(String placeHolderPath, String placeholder) {
                      String localizedPath = File.separator;
              
                      StringTokenizer tok = new StringTokenizer(placeHolderPath, placeholder);
                      while(tok.hasMoreTokens()){
                          localizedPath +=  tok.nextToken() + File.separator;
                      }
              
                      return localizedPath;
                  }
              Olek
              • 4. Re: File separator problem
                807588
                So what was wrong with just using
                replaceAll( "\\$", File.separator );

                P.S. I have never found any of this necessary as long as content is to be used to construct a File object because '/' can then be used regardless of the OS.

                Edited by: sabre150 on May 16, 2009 3:55 PM