文件的創建時間通過該文件的屬性獲取,注釋部分為獲取文件的最后修改時間(通過lastModified()獲取)。
代碼為刪除創建范圍內的文件:
1 package eg2; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.nio.file.Files; 6 import java.nio.file.LinkOption; 7 import java.nio.file.Path; 8 import java.nio.file.Paths; 9 import java.nio.file.attribute.BasicFileAttributeView; 10 import java.nio.file.attribute.BasicFileAttributes; 11 import java.text.ParseException; 12 import java.text.SimpleDateFormat; 13 import java.util.Date; 14 import java.util.Scanner; 15 16 /****************** 17 * 文件的刪除 18 *******************/ 19 public class Test2_2 { 20 21 static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 22 static Date CreateTimeDate; 23 24 public static void main(String[] args) throws ParseException { 25 // TODO Auto-generated method stub 26 27 @SuppressWarnings("resource") 28 Scanner sc = new Scanner(System.in); 29 System.out.println("請輸入指定文件夾:"); 30 String dirs = sc.next(); 31 int[] a = new int[6]; 32 int[] b = new int[6]; 33 System.out.println("請輸入起始時間t1:"); 34 for (int i = 0; i < 6; i++) 35 a[i] = sc.nextInt(); 36 System.out.println("請輸入最終時間t2:"); 37 for (int i = 0; i < 6; i++) 38 b[i] = sc.nextInt(); 39 String t1 = "", t2 = ""; 40 t1 = t1 + a[0] + "-" + a[1] + "-" + a[2] + " " + a[3] + ":" + a[4] + ":" + a[5]; 41 t2 = t2 + b[0] + "-" + b[1] + "-" + b[2] + " " + b[3] + ":" + b[4] + ":" + b[5]; 42 System.out.println(t1); 43 System.out.println(t2); 44 Date date1 = df.parse(t1); 45 Date date2 = df.parse(t2); 46 System.out.println("要刪除的文件名為:"); 47 delete(dirs, date1, date2); 48 System.out.println("操作結束!"); 49 } 50 51 private static void delete(String dirs, Date date1, Date date2) throws ParseException { 52 // TODO Auto-generated method stub 53 54 File dir = new File(dirs); 55 File[] list = dir.listFiles(); 56 for (File file : list) { 57 if (file.isDirectory()) { 58 if (file.list().length > 0) { 59 delete(file.getAbsolutePath(), date1, date2); 60 } 61 } else { 62 Path p = Paths.get(file.getPath()); 63 BasicFileAttributeView basicview = Files.getFileAttributeView(p, BasicFileAttributeView.class, 64 LinkOption.NOFOLLOW_LINKS);//通過文件的屬性來獲取文件的創建時間 65 BasicFileAttributes attr; 66 try { 67 attr = basicview.readAttributes(); 68 CreateTimeDate = new Date(attr.creationTime().toMillis()); 69 // DateFormat usdf = new SimpleDateFormat("EEE MMM dd 70 // HH:mm:ss zzz yyyy", Locale.US); 71 // Date date = usdf.parse(CreateTimeDate.toString()); 72 // String fileTime = df.format(date); 73 // Date fileTimes = df.parse(fileTime); 74 // if (date1.getTime() <= file.lastModified() && 75 // file.lastModified() <= date2.getTime()) { 76 // }//這部分為文件的最后修改時間 77 if (date1.getTime() <= CreateTimeDate.getTime() && CreateTimeDate.getTime() <= date2.getTime()) { 78 System.out.println(file.getName()); 79 file.delete(); 80 } 81 } catch (IOException e) { 82 // TODO Auto-generated catch block 83 e.printStackTrace(); 84 } 85 } 86 } 87 } 88 }