ITeye博客

File.separator

冷h锋 · 2016-05-10 14:29 · java · 编程语言 · Markdown

在windows中的文件分隔符是 \ 和 /都可以

但是在Linux中,文件分隔符只能是/

所以用了\的程序在Linux下会出问题。

而File.separator是系统默认的文件分割符号,屏蔽了这些系统的区别。

用File.separator保证了在任何系统下不会出错。

在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常。

比如说要在temp目录下建立一个test.txt文件,在Windows下应该这么写:


File file1 = new File ("C:\tmp\test.txt");


在Linux下则是这样的:
File file2 = new File ("/tmp/test.txt");

如果要考虑跨平台,则最好是这么写:


File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");

File类有几个类似separator的静态字段,都是与系统相关的,在编程时应尽量使用。


File.separator

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。