-1

I need to rename some paths in database.
I rename folder:

String mainFolder= "D:\test\1\data"; //folder renamed from fd

Then i need to rename all files and directories inside that folder:

    String file1="D:\test\1\fd\dr.jpg";
    String folder1="D:\test\1\fd\fd"; // in this case last fd needs to be renamed
    String folder2="src/fd/fd/"; //fake path also needs to be renamed

What is the best and fastest way to rename that strings?
My thoughts about "/":

        String folder2= "src/da/da";
        String[] splittedFakePath = folder2.split("/");
        splittedFakePath[splittedFakePath.length - 2] = "data";

        StringBuffer newFakePath = new StringBuffer();
        for (String str : splittedFakePath) {
            newFakePath.append(str).append("/");
        }

String after rename: src/data/da/
But when im trying split by "\":

Arrays.toString(Pattern.compile(File.separator).split(folder1));

I receive:

java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^
4
  • Did you remember to escape the backslash ("\\\\")? Commented Jan 26, 2016 at 22:10
  • Backslash is a special character in regexes. You need to double it or use Pattern.compile(File.separator,Pattern.LITERAL). Commented Jan 26, 2016 at 22:11
  • 1
    \ is special in String literal but also in regular expression engine which split is using so you need to escape it twice: once in regex \\ and second time in String "\\\\". Commented Jan 26, 2016 at 22:11
  • It actually works with "\\\\" Commented Jan 26, 2016 at 22:16

1 Answer 1

0

Look into java's String replace(...) method.

It is wonderful for string replacement, much better than attempting a regex.

Keep in mind that real directory handling has a few special cases, which don't lend themselves well to direct string manipulation. For example '//' often gets compacted to '/' in Unix like systems, and if you care about proper directory corner-cases, then use the Java Path class

Sign up to request clarification or add additional context in comments.

2 Comments

When i get a path of the file i receive string with "\" . Is it necessary to replace "\" with "/" before save them to database?
@RuslanLomov Remember that in Java, the character '\' is an escape indicator, for example '\n' is a newline, '\t' is a tab. To get a single character you need to escape the slash, like so '\\'. Also, I don't know what your database's requirements are, but those requirements are more important than my opinion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.