package p.file.demo;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import javax.naming.directory.DirContext;
import com.sun.org.apache.xalan.internal.xsltc.dom.SAXImpl.NamespaceWildcardIterator;
public class FileMethodDemo {
public static void main(String[] args) throws IOException {
/*
* File对象的常见方法
*
* 1 获取
* 1.1获取文件名称
* 1.2获取文件路径
* 1.3获取文件大小
* 1.4获取文件修改时间
* 2 创建与删除
*
* 3 判断
*
* 4 重命名
*
*
*/
//creatAndDeleteDemo();
//getDemo();
//isDemo();
//renameToDemo();
listRootDemo();
}
private static void listRootDemo() {
File file=new File("d:\\");
System.out.println("getFreeSpace:"+file.getFreeSpace());
System.out.println("getTotalSpace:"+file.getTotalSpace());
System.out.println("getUsableSpace:"+file.getUsableSpace());
/*File[] files=File.listRoots();
for(File file:files) {
System.out.println(file);
}*/
}
private static void renameToDemo() {
File f1=new File("d:\\3.mp3");
File f2=new File("e:\\aa.mp3");
f1.renameTo(f2);//同一路径下重命名 不同路径剪切和重命名
}
private static void isDemo() {
File f=new File("aaa.txt");
f.mkdir();
/*boolean b=f.exists();
System.out.println("b="+b);*/
//最好先判断是否存在
System.out.println(f.isFile());
System.out.println(f.isDirectory());
}
public static void creatAndDeleteDemo() throws IOException {
//File dir=new File("aa//asd//asd//asd//as//da");
//dir.mkdirs();//创建多级目录
//File dir=new File("abc");
//boolean b=dir.mkdirs();//make directory 创建文件夹
//System.out.println("b:"+b);
//dir.delete();//删除文件夹 文件夹中有内容就不会删除 正在被操作也不会被删除
//文件的创建和删除
/* File file=new File("file.txt");
//boolean b=file.createNewFile();
*和输出流不一样,如果文件不存在 则创建 如果文件存在 则不创建
*
boolean b=file.delete();
System.out.println("b="+b); */
}
public static void getDemo() {
File file=new File("a.txt");//相对
File file2=new File("c://a.txt");//绝对
String name=file.getName();
String absPath=file.getAbsolutePath();//绝对路径
String path=file.getPath();//
long len=file.length();
long time=file.lastModified();
Date date=new Date(time);
DateFormat dateformat=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
String str_time=dateformat.format(date);
System.out.println("parent"+file.getParent());
System.out.println("name"+name);
System.out.println("absPath"+absPath);
System.out.println("path"+path);
System.out.println("len"+len);
System.out.println("time"+str_time);
}
}
Java IO File对象 常见功能
最新推荐文章于 2023-12-02 22:49:43 发布