String used for a file name has escape character “

2019-08-09 15:58发布

问题:

PrintWriter out = 
 new PrintWriter("C:\Users\Slerig\Desktop\gnuplot\binary\cannonballOutput.txt");


This is my sample code. It is quite simple. It throws a "Invalid Escape Character" error because of the backslashes. How do I get around this? Programming in Java btw.

回答1:

You'll have to escape \ with \\ in your string (or use / instead) Use

PrintWriter out = 
 new PrintWriter("C:\\Users\\Slerig\\Desktop\\gnuplot\\binary\\cannonballOutput.txt");


回答2:

You can also use / and Java will convert them automatically if you don't want to litter your paths with \\.

public class Test
{
    public static void main(final String[] args)
    {
        final File f = new File("C:/tmp");
        for (String s : f.list())
        {
            System.out.println("filename = " + s);
        }
    }
}


回答3:

To escape a \ you just need to use \\ so:

new PrintWriter("C:\\Users\\Slerig\\Desktop\\gnuplot\\binary\\cannonballOutput.txt");