Thor
Thor

Reputation: 10068

Error: illegal escape character - when trying to create a path

I'm new to Java and is trying to learn how to create a path. Below is the code I wrote:

import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Path;

public class CopyBytes {
    public static void main(String[] args) throws IOException {

        Path p1 = Paths.get("C:\Users\Justin\Documents\NetBeansProjects\JavaApplication\xanadu1.txt");
    }
}

However, when I run the code, the IDE output error:

Illegal escape character.

Why is this happening?

Upvotes: 1

Views: 14969

Answers (2)

user3437460
user3437460

Reputation: 17454

Certain characters have special meaning when used in a String in Java (and many other languages).

A backward slash \ can be used to escape a character. Some valid escape characters in Java are like \t for tabs and \n for newlines.

Hence if you use only a single \. The compiler will assume that you are trying to create an escape sequence for:

\U, \J, \D, \N, \x  

and these escape sequences do not exist, hence giving you the error.


If you are using \ you have to escape it to \\.

But if you use / a forward slash, you don't have to.

So you can have a path like this:

"C:\\Users\\Justin\\Documents\\NetBeansProjects\\JavaApplication\\xanadu1.txt"

or like this:

"C:/Users/Justin/Documents/NetBeansProjects/JavaApplication/xanadu1.txt"

Upvotes: 5

TorbenJ
TorbenJ

Reputation: 4582

Like @Satya said you have to use double backward slashes \\.
A single \ starts a so called escape sequence to express several special (non-printable) characters.

You can find more about escape sequences in this Wikipedia article

Upvotes: 2

Related Questions