断弯刀

导航

正斜杠(/)与反斜杠(\)

正斜杠(/)与反斜杠(\)区别           https://www.cnblogs.com/zuoguanglin/archive/2012/02/23/2364528.html        slash       backslash            

  关于str.split(",")中间 什么时候该加\\转义        https://www.cnblogs.com/tnsay/p/5750644.html

  Unix/Linux中,Windows路径    正斜杠和反斜杠         https://zhidao.baidu.com/question/557013141.html

 


 

那为什么Java中写正斜杠“/”、“//”、“///”,甚至再多都不会有问题呢?

为了转义,是反斜杠“\\”,两个反斜杠实际代表一个反斜杠“\”。

那是因为Java中处理流,都会使用到File这个类,在Windows环境中,File会使用WinNTFileSystem
这个工具类处理那些问题,再WinNTFileSystem类中,会把所有的正斜杠“/”都处理成反斜杠,再把多余的反斜杠“\”给去掉,最终会表示成转义后的一个反斜杠。

  • 测试
package com.zjx.crawler;

import java.io.File;

public class Test02 {

    public static void main(String[] args) throws Exception{
        File file=new File("d:"+File.separator+"aasoftware"+File.separator+"test.txt");  
        System.out.println("file:"+file);    //file:d:\aasoftware\test.txt
        
        /**
         * 报错
         * Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )
         */
        String filePath5="D:\aasoftware\test01";      
        
        String filePath2="D:\\aasoftware\\test01";      
        File file2=new File(filePath2);
        System.out.println("file2:"+file2);      //file2:D:\aasoftware\test01
        
        String filePath3="D:/aasoftware/test01";
        File file3=new File(filePath3);
        System.out.println("file3:"+file3);        //file3:D:\aasoftware\test01
        
         File file4 = new File("C:\\\\\\Users///pc//////////Desktop\\工作日志.txt");
         System.out.println("file4:"+file4.getAbsolutePath());       //file4:C:\Users\pc\Desktop\工作日志.txt
    }
}

 getAbsolutePath()的源代码为:

public String getAbsolutePath() {
    return fs.resolve(this);
}

而这个fs在Windows平台下正是WinNTFileSystem这个类:

WinNTFileSystem则处理了这些事情。

posted on 2018-10-16 11:08  断弯刀  阅读(1012)  评论(0编辑  收藏  举报