这些方法也都是File类内置的成员方法,无需我们写,直接拿来用即可。
基本获取
public class Demo {
public static void main(String[] args) {
File file=new File("E:\\Demo\\a.txt"); System.out.println("绝对路径:"+file.getPath());
System.out.println("相对路径:"+file.getAbsolutePath());
System.out.println("名字:"+file.getName());
System.out.println("大小/字节长度:"+file.length());
System.out.println("最后修改时间:"+file.lastModified()); //最后修改是从1970年到现在毫秒,而不是具体日期。下边格时间式化成日期。
Date d=new Date(file.lastModified());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("最后修改时间:"+sdf.format(d));
}
}
高级获取
File.list方法
public class Demo {
public static void main(String[] args) {
File file=new File("E:\\");
//获取指定目录下所有文件或文件夹名字的数组,所以是字符串数组
String[] Strarray=file.list(); for(int i=0; i<Strarray.length; i++)
System.out.println(Strarray[i]);
}
}
$RECYCLE.BIN
80.jpg
Demo
System Volume Information
歌曲
电影
美图
File.listFile方法
public class Demo {
//File.list方法
public static void main(String[] args) {
File file=new File("E:\\");
//获取指定目录下所有文件或文件夹对象的数组,所以是(文件)对象串数组
File[] Strarray=file.listFiles(); for(int i=0; i<Strarray.length; i++)
System.out.println(Strarray[i].getName());
}
}
$RECYCLE.BIN
80.jpg
Demo
System Volume Information
歌曲
电影
美图