很多朋友都想知道java file.exists()的用法有哪些?下面就一起来了解一下吧~
java.io.File.exists() 用来测试抽象路径名定义的文件或目录是否存在。
1 语法
public boolean exists()
2 返回值
当且仅当由抽象路径名确定文件是否存在,则该方法返回布尔值true;否则为false。
3 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* java.io.File.exists()方法的例子
*/
import java.io.File;
public class Demo {undefined
public static void main(String[] args) {undefined
File f = null;
boolean bool = false;
try {undefined
// create new files
f = new File("test.txt");
// create new file in the system
f.createNewFile();
// tests if file exists
bool = f.exists();
// prints
System.out.println("File exists: "+bool);
if(bool == true) {undefined
// delete() invoked
f.delete();
System.out.println("delete() invoked");
}
// tests if file exists
bool = f.exists();
// prints
System.out.print("File exists: "+bool);
} catch(Exception e) {undefined
// if any error occurs
e.printStackTrace();
}
}
}
输出结果为:
File exists: true
delete() invoked
File exists: false以上就是小编今天的分享,希望能帮到大家。