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?
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"