Windows escape sequence issue with file path in java

前端 未结 6 1594
误落风尘
误落风尘 2020-12-07 05:00

I need to use windows file path to do some operation on files but i am getting invalid escape sequence error.

File f = new File(\"C:\\test\");
6条回答
  •  执笔经年
    2020-12-07 05:48

    File f = new File("C:\\test"); is correct.

    You are not creating a File with the path "C:\\test" here. You are creating a File with the path "C:\test". The \\-to-\ conversion happens when you compile the program - by the time your program is running, the double backslashes are gone.

    The same for String - String s = "C:\\test"; does not create a string with two backslashes, only one.

    You can think of it this way: the string does not actually have two backslashes, but you have to write it that way to put it in your code.

    You might be wondering why that is - it's because backslashes are used to insert special characters in strings. When you type \t in a string it inserts a tab, for example. If you want to insert a backslash, then t, you type \\t.

提交回复
热议问题