File类是java.io包中唯一代表磁盘文件本身的对象。
可以通过调用File类中的方法创建、删除、重命名文件等操作。
File类的对象主要用来获取文件本身的一些信息,如文件所在的目录、文件的长度、文件的读写权限。
import java.io.File;
public class Creatfile {
public static void main(String [] args)
{
File file = new File("work.txt");//创建文件对象
if(file.exists())//如果文件存在
{
file.delete();//删除文件
System.out.println("file is delete.");
}
else
{
try{
String name = file.getName();
long length = file.length();
System.out.println("name:"+name);
System.out.println("lengt:"+length);
file.createNewFile();//创建文件
System.out.println("creat file");
}
catch(Exception e){
e.printStackTrace();
}
}
}
}