File文件方法使用

exists()                     //测试文件是否存在

getAbsolutePath()  //返回绝对路径名

getName()              //返回此文件名

getParent()             //返回上一级,如果没有上一级,就返回null

delete()                   //删除此对象文件

createNewFile()      //创建空文件,不创建文件夹

isDirectory()           //测试该对象表示的是否是目录

mkdir()                   //创建一个目录,它的路径由当前File对象指定

mkdirs()                 //创建包含父目录的目录


示例:创建一个新的文件

public void creat(File file){
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("文件创建成功!");

示例:获取文件信息

public static void main(String[] args) {
File file = new File("
d:/11.txt");
try {
if (!file.
exists()) {
file.
createNewFile();
}else{
System.out.println("名字"+file.
getName());
System.out.println("相对路径"+file.
getPath());
System.out.println("绝对路径"+file.
getAbsolutePath());
System.out.println("字节数"+file.
length());
}
} catch (IOException e) {
e.printStackTrace();

猜你喜欢

转载自blog.csdn.net/jinqianwang/article/details/80099275