Java-不要删除与任何数组值匹配的文件

时间:2018-08-10 02:17:42

标签: java

我有一个文件列表(大约500个或更多文件),其中文件名包含一个日期。

file_20180810

file_19950101

file_20180809

我要删除的文件超出存储期限。 到目前为止,我已经提出了以下逻辑

  

〜获取有效存储期的日期(即,如果存储期为5天,今天的日期为20180810,则在数组中存储日期值20180810、20180809、20180808、20180807、20180806、20180805。

     

〜检查目录中的每个文件是否包含以下任何日期。如果包含日期,请不要删除,否则请删除。

我的问题是,如果文件名确实包含一个日期,并且我使用循环来删除文件,则它也可能删除具有有效日期的其他文件。为了以代码形式显示我想做的事情,它像这样:

 if (!fileName.contains(stringDate1) && 
 !fileName.contains(stringDate2) && 
 !fileName.contains(stringDate3)) //...until storage period
 {//delete file}

有没有更好的表达方式?有任何解决方法的建议吗? 请,谢谢。

5 个答案:

答案 0 :(得分:1)

您可以尝试使用Regex提取每个文件的实际日期,并检查是否包含在有效期内。

Pattern p = Pattern.compile("file_(?<date>\d{6})");
foreach(File f : filelist){
    Matcher m = p.matcher(f.filename());
    if(m.find()){
        Date fileDate = new Date(m.group("date"));
        if(fileDate.before(periodStartDate)){
            file.delete();
        }
    }
}

代码不够精确,不应该编译,请检查Date对象的创建和比较,但是主要思想在这里很多。

答案 1 :(得分:1)

从文件名中解析日期。这是一个示例:

myproject python-home=/home/ubuntu/Django/myvenv python-path=/home/ubuntu/Django/myproject

答案 2 :(得分:0)

您只能删除不在阵列中的文件,例如(已测试,正在运行):

    String path = ""; // <- Folder we want to clean.

    DateFormat df = new SimpleDateFormat("yyyyMMdd"); // <- DateFormat to convert the Calendar dates into our format.
    Calendar cal = Calendar.getInstance(); // <- Using Calendar to get the days backwards.
    ArrayList<String> dr = new ArrayList<String>(); // <- Save the dates we want to remove.    dr = don't remove

    dr.add(df.format(cal.getTime())); // <- add the actual date to List
    for(int i = 0; i < 5; i++) { // <- Loop 5 Times to get the 5 Last Days
        cal.add(Calendar.DATE, -1); // <- remove 1 day from actual Calendar date
        dr.add(df.format(cal.getTime())); // <- add the day before to List
    }

    for(File file : new File(path).listFiles()) { // <- loop through all the files in the folder
        String filename = file.getName().substring(0, file.getName().lastIndexOf(".")); // <- name of the file without extension

        boolean remove = true; // <- Set removing to "yes"
        for(String s : dr) { // <- loop through all the allowed dates
            if(filename.contains(s)) { // <- when the file contains the allowed date
                remove = false; // <- Set removing to "no"
                break; // <- Break the loop for better performance
            }
        }

        if(remove) { // <- If remove is "yes"
            file.delete(); // <- Delete the file because it's too old for us!
        }
    }

但这不是最好的方法!更好的方法是计算文件的年代。由于_,您可以很容易地从文件名中获取日期。喜欢(未经测试):

    String path = ""; // <- Folder we want to clean.
    Date today = new Date();
    DateFormat df = new SimpleDateFormat("yyyyMMdd"); // <- Dateformat you used in the files
    long maxage = 5 * 24 * 60 * 60 * 1000; // <- Calculate how many milliseconds ago we want to delete

    for(File file : new File(path).listFiles()) { // <- loop through all the files in the folder
        String fds = file.getName().split("_")[1]; // <- Date from the filename as string
        try {
            Date date = df.parse(fds); // Convert the string to a date

            if(date.getTime() - today.getTime() <= maxage) { // <- when the file is older as 5 days 
                file.delete(); // <- Delete the file
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

答案 3 :(得分:0)

这是一些示例代码,该代码演示如何对照提供的一组日期字符串(例如“ 20180810”)验证输入文件列表(文件名字符串,例如“ file_20180810”)并执行操作(例如删除文件)。

import java.util.*;
import java.io.*;
public class FilesTesting {
    private static final int DATE_STRING_LENGTH = 8; //  length of 20180809
    public static void main(String [] args) {
        List<String> filter = Arrays.asList("20180810", "20180808", "20180809", "20180807", "20180806", "20180805");
        List<File> files = Arrays.asList(new File("file_20180810"), new File("file_19950101"), new File("file_20180809"));
        for (File file : files) {
            String fileDateStr = getDateStringFromFileName(file.getName());
            if (filter.contains(fileDateStr)) {
                // Do something with it
                // Delete file - if it exists
                System.out.println(file.toString());
            }
        }
    }
    private static String getDateStringFromFileName(String fileName) {
        int fileLen = fileName.length();
        int dateStrPos = fileLen - DATE_STRING_LENGTH;
        return fileName.substring(dateStrPos);
    }
}

答案 4 :(得分:-2)

如果您使用的是ES6,则可以使用数组包含并返回true或false进行验证。

['a', 'b', 'c'].includes('b')