How to replace backslash with forward slash in Java [2 ways]

In this post, I will be sharing how to replace a backslash with a forward slash in Java with examples. There are two ways to achieve our goal of replacing a backslash with a forward slash:

1. Using replace() method

2. Using replaceAll() method

Read Also: Replace Space with Underscore in Java

Let's dive deep into the topic:

Replace Backslash with Forward slash in Java

Backslash in Java is used as an escape character. 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 replace() method 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 replaceAll() method 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.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry