Java File.exists 文件或文件夹是否存在
定义
public boolean exists()返回
true:表示文件或者文件夹已经存在,false:表示不存在
异常SecurityException:SecurityManager.checkRead(String)方法拒绝对目录的读取访问
实例
public static void main(String[] args) throws Exception { //判断文件是否存在如果存在就删除,不存在就新建 String path = "F:\\51gjie"; String filename = "testfile.txt"; File file = new File(path, filename); //判断文件或文件夹是否存在 boolean flag = file.exists(); if(flag) { //文件存在就要删除文件 file.delete(); } else { //文件不存在就要新建文件 file.createNewFile(); } }
此方法可以同时判断文件和文件夹是否存在
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。