0

I have a file path like this

\\ptrisf02\group\Corrolog\Other\Newfolder\SecurityTest\EV10222-01\FinalPack\REP WI\3101384589-(PN-5A1662).pdf

I want to replace \\ to \\\\ and \ to \\ . I wrote this code for it

String r_Docpath=Docpath.replace('\\', '\\\\');

But it gives Invalid character constant error. How can I made it correctly?

I solved the problem like this codes;

String r_Docpath=Docpath.replace("\"", "\\\"");
String r2_Docpath=r_Docpath.replace("\\", "\\\\\"");
  • 2
    I sense an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). Why would you want to change each backslash to two backslashes? Clearly, the path is valid as it is. – VGR Sep 06 '19 at 15:40

1 Answers1

4

In Java ' is used to create char literal which can represent only one character (char is type which holds 16 bits and JVM uses UTF-16 encoding so it can store only one character - or even half in case of characters created via surrogate-pairs). So when you write '\\\\' it is like writing 'ab' which as you see is attempt to place two characters in single char literal, which causes compiler to complain.

To group zero or more characters in one structure we use String type. You can create String literal with " instead of '.

So what you are after seems to be

String r_Docpath = Docpath.replace("\\", "\\\\");

BTW you shouldn't name variables starting with upper-case in Java, so instead of Docpath use docpath or even docPath. Style like Docpath or DocPath where first character is uppercase is reserved for classes, interfaces, enums like String List TimeUnit etc.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 2
    Good Answer. I would add a note that `char` type is now outmoded, as it cannot represent all Unicode characters. Instead we use integer numbers as [code points](https://en.wikipedia.org/wiki/Code_point). – Basil Bourque Sep 06 '19 at 14:52