Java程序中文件目录的跨平台 --- File.separator的作用

最近在看别人的代码,有一段代码中有File.separator,然后就翻阅了一下资料,发现这是一段挺好的跨平台代码,写博客以记之



比如说你要在D盘下的temp目录下创建一个Demo.txt
在Windows下你会这样写:

File file = new File("D:\temp\Demo.txt");

而在Linux下你要这样写:

File file = new File("/temp/Demo.txt");

如何你把Windows下的Java程序部署到Linux的服务器上去,这段代码就会出问题,因为文件路径不对,如过要跨平台,你需要这样写:

File file = new File("C:"+File.separator+"temp"+File.separator+"Demo.txt");

这里的File.separator就代表了不同系统目录中的分隔符,如过这段代码在Windows下,就解析为\,如果在Linux下的就为/

下面写一段代码跑一下:

public class TestFile {
    public static void main(String[] args) throws IOException {
        File file = new File("D:"+File.separator+"demo.txt");
        System.out.println("file: " + file);
        if(file.exists()){
            file.delete();
            System.out.println("执行了删除文件!");
        }else {
            file.createNewFile();
            System.out.println("执行了创建文件");
        }
    }
}

代码执行结果为: 
file: D:\demo.txt
执行了删除文件!
Process finished with exit code 0

注: 我的demo.txt之前存在

你可能感兴趣的:(Java)