Replace Backslash with Forward Slash in Java

1. Introduction

In this post, we will learn about how to replace backslash with forward slash in java.

backslash() is used as escape character in Java. For example:
It can be used to:

  • Used in special characters such as new line character \n, tab \t
  • Write unicode characters like \u%04x.

That’s the reason we can’t directly replace backslash to forward slash. We need to escape it while replacing it.

Let’s go through different ways to do it.

2. Using replace() Method

Use String’s replace() method to replace backslash with forward slash in java.

String’s replace() method returns a string replacing all the CharSequence to CharSequence.
Syntax of replace() method:

public String replace(CharSequence target, CharSequence replacement)  

Here is an example:

String str = "C:\\tempDir\\temp.txt";
str = str.replace("\\","/");
System.out.println(str);

Output:

C:/tempDir/temp.txt

As you can see, replace() method replaceed each space with underscore.

3. Using replaceAll() method

Use replaceAll() method to replace backslash with forward slash in java. It is identical to replace() method, but it takes regex as argument.Since the first argument is regex, you need double escape the backslash.

Here is syntax of replaceAll method:

public String replaceAll(String regex, String replacement)  
String str = "C:\\tempDir\\temp.txt";
str = str.replaceAll("\\\\","/");
System.out.println(str);

Output:

C:/tempDir/temp.txt

That’s all about how to replace backslash with forward slash in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.