
本文能实例来演示File类常用操作,示例程序打印出指定文件夹的所有子文件夹和数据文件,并打印出相关的修改日期和文件大小属性。
² 。
示例代码: public class Test { public static void main(String[] args) { File file = new File("C:\\Program Files\\Java\\jdk1.8.0_111"); File[] ff=file.listFiles(); for(File f:ff){ if(f.isDirectory()){ System.out.println(f.getName()+"\t文件夹"); } } for(File f:ff){ if(f.isDirectory()){ System.out.println(f.getName()+"\t\t\t\t\t"+getModifiedDate(f)+"\t\t\t文件夹"); } } for(File f:ff){ if(f.isFile()){ System.out.println(f.getName()+"\t\t\t\t\t"+getModifiedDate(f)+"\t\t\t"+getFileSize(f)); } } } public static String getModifiedDate(File file){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm"); Date modifiedDate=new Date(file.lastModified()); String str=sdf.format(modifiedDate); return str; } public static String getFileSize(File file){ long len=file.length(); double kb=len%1024==0?len/1024:len/1024+1; return kb+"KB"; } } | 运行程序,结果如下:
bin 文件夹 db 文件夹 include 文件夹 jre 文件夹 lib 文件夹 bin 2016-11-22 09:00 文件夹 db 2016-11-22 09:00 文件夹 include 2016-11-22 09:00 文件夹 jre 2016-11-22 09:00 文件夹 lib 2016-11-22 09:01 文件夹 COPYRIGHT 2016-09-22 07:47 4.0KB javafx-src.zip 2016-11-22 09:00 4972.0KB LICENSE 2016-11-22 09:00 1.0KB README.html 2016-11-22 09:00 1.0KB release 2016-11-22 09:01 1.0KB src.zip 2016-09-22 07:47 20757.0KB THIRDPARTYLICENSEREADME-JAVAFX.txt 2016-11-22 09:00 108.0KB THIRDPARTYLICENSEREADME.txt 2016-11-22 09:00 173.0KB |
|
|