Windows escape sequence issue with file path in ja

2020-02-07 06:30发布

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");

the system accepts only " \\ " or "/" but if I copy file path from windows it is with "\". how can i solve this issue

6条回答
做个烂人
2楼-- · 2020-02-07 07:09

Use File.seperator in place of "\".

File f = new File("C:"+File.seperator+"test");

File.seperator returns "\" and it is not treated as an escape character.

If your file test.txt is saved in folder D:/MyFloder/MyPrograms you can do something like this

File f = new File("D:"+File.seperator+"MyFloder"+File.seperator+"MyPrograms"+File.seperator+"test.txt");

EDIT

You don't need to worry about OS

For Unix : File.separator = /

For Windows : File.separator = \

查看更多
姐就是有狂的资本
3楼-- · 2020-02-07 07:14

\ is the escape character in Java Strings. Use \\ instead.

"C:\\test" resolves to the String C:\test

查看更多
够拽才男人
4楼-- · 2020-02-07 07:18

Use java.nio.file.Path instead of java.io, you'll not have problem with escape sequence character :

import java.nio.file.Path;
import java.nio.file.Paths;
    Path path = Paths.get("C:\test");
查看更多
劫难
5楼-- · 2020-02-07 07:21

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.

查看更多
看我几分像从前
6楼-- · 2020-02-07 07:27

You can use \\ or / but / is better because it is OS-independent.

Replace the single backslash in the path with a double backslash or a single forward slash to solve your issue.

Internally, Java will convert it to the file seperator of the OS

查看更多
萌系小妹纸
7楼-- · 2020-02-07 07:35

you can use '/' (as in Linux) in paths since Windows XP, so forget about \

查看更多
登录 后发表回答