How to replace backslash with forward slash in Java [2 ways]
1. Using replace() method
2. Using replaceAll() method
Read Also:
Let's dive deep into the topic:
Replace Backslash with Forward slash in Java
Backslash in Java is used as an . For example:a. Writing unicode characters like \uFFFF.
b. Writing special characters like tab(\t) and newline character(\n)
1. Using replace() method
We can easily replace backslash with forward slash by using as shown below in the example.
public class ReplaceBackslashWithForwardSlash { public static void main(String args[]) { String str = "C:\\tempFolder\\temp.txt"; str = str.replace("\\","/"); System.out.println(str); } }
Output:
C:/tempFolder/temp.txt
2. Using replaceAll() method
We can also use the to replace a backslash with a forward slash in Java.
Note:
The syntax of the replaceAll() method is identical to replace() method in Java but it takes regex as the first argument.
To replace backslash with forward slash using the replaceAll() method, you need to double escape the backslash since the first argument is regex. You can find the example below:
public class ReplaceBackslashWithForwardSlash2 { public static void main(String args[]) { String str = "C:\\tempFolder\\temp.txt"; str = str.replaceAll("\\\\","/"); System.out.println(str); } }
Output:
C:/tempFolder/temp.txt
That's all for today. Please mention in the comments if you have any questions related to how to replace a backslash with a forward slash in Java with examples.