Java程序中文件目录的跨平台 --- File.separator的作用
2017-08-09 16:20
260 查看
最近在看别人的代码,有一段代码中有
比如说你要在D盘下的temp目录下创建一个Demo.txt
在Windows下你会这样写:
而在Linux下你要这样写:
如何你把Windows下的Java程序部署到Linux的服务器上去,这段代码就会出问题,因为文件路径不对,如过要跨平台,你需要这样写:
这里的File.separator就代表了不同系统目录中的分隔符,如过这段代码在Windows下,就解析为
下面写一段代码跑一下:
注: 我的demo.txt之前存在
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中File文件路径跨平台(File.separator)
- java小程序,用java在指定目录或以及子目录中找出同名文件,java File过滤文件名后找同名文件
- java程序的递归算法,列出某个目录下的所有子目录和文件
- java文件操作整理(一)--递归删除目录和文件的程序
- java程序的递归算法,列出某个目录下的所有子目录和文件
- java程序的递归算法 列出某个目录下的所有子目录和文件
- linux平台中java程序文件编码错误一例
- java.io.File的两个运用实例-文件的删除及树形目录
- java文件过滤器(File类listFiles方法可选参数)--获取目录下指定的某类文件
- java文件操作整理(一)--递归删除目录和文件的程序
- linux中,运行java程序装载linux指定目录下的Properties文件
- [06-03] 用MASM32写的文件目录监视程序FileDirMon
- 使用JSmooth将java程序转换成windows上的.exe文件(彻底解决相对目录问题)
- 分享非常有用的Java程序 (关键代码) (二)---列出文件和目录
- 一个使用多线程删除指定目录及子目录下所有指定文件的Java程序(源码)
- java File的基本操作实例(目录及文件的 新建/拷贝/移动)
- 使用JSmooth将java程序转换成windows上的.exe文件(彻底解决相对目录问题)
- 编写一个程序,将d:\yy目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.txt
- java程序的递归算法,列出某个目录下的所有子目录和文件
- java程序的递归算法,列出某个目录下的所有子目录和文件