Java是否处理多个斜杠\\\\\\&引用;“作为单一的”\\&引用;在文件路径中?
下面的行和注释行产生相同的结果:Java是否处理多个斜杠\\\\\\&引用;“作为单一的”\\&引用;在文件路径中?,java,string,Java,String,下面的行和注释行产生相同的结果: public class StringEscapeMain { public static void main(String[] args){ String fileName = "C:\\Dev\\TryEclipseJava\\StringEscape\\\\\\f.txt"; /* String fileName = "C:\\Dev\\TryEclipseJava\\StringEscape\\f.txt";*/
public class StringEscapeMain {
public static void main(String[] args){
String fileName = "C:\\Dev\\TryEclipseJava\\StringEscape\\\\\\f.txt";
/* String fileName = "C:\\Dev\\TryEclipseJava\\StringEscape\\f.txt";*/
File file = new File(fileName);
if(file.exists()){
System.out.println("File exists!");
}
else{
System.out.println("File does not exist!");
}
}
}
Java是否总是将任何超过2个斜杠的斜杠序列视为“\”
谢谢 不,Java不会将这些字符串视为相同的字符串。文本
\
必须在前面加上另一个\
进行转义
所以\
是一个反斜杠,\
是三个
只有在平台上使用字符串作为
\
文件的路径时,\
才是分隔符(Windows…),额外的反斜杠才会被去除。请参阅用户6690200提供的更详细信息。第一个\
用于转义,这意味着
将被编译为C:\\Dev\\TryEclipseJava\\StringEscape\f.txt
C:\Dev\TryEclipseJava\StringEscape\\\\f.txt
将被编译为C:\\Dev\\TryEclipseJava\\StringEscape\\f.txt
C:\Dev\TryEclipseJava\StringEscape\f.txt
使用以下内容创建
文件
实例时:
File file = new File(fileName);
文件名将根据您的文件系统“规范化”:
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}
在WinNTFileSystem的“规范化”过程中
C:\Dev\TryEclipseJava\StringEscape\\\\f.txt
将被截断为:
C:\Dev\TryEclipseJava\StringEscape
然后它将:
从路径的其余部分删除多余的斜杠,强制所有
将斜杠改为首选斜杠
最后,fileName
标准化为:
C:\Dev\TryEclipseJava\StringEscape\f.txt
消除额外反斜杠的不是Windows,而是Java文件
类,它肯定以特殊方式处理\
。