怎么在码头做家务?

时间:2015-05-26 07:57:03

标签: java webserver jetty

我们允许用户将一些图像文件上传到我们的网络服务器。上传后10-15分钟这些文件没有用。有没有办法自动删除这些文件,例如所有已过期的图片文件'他们的名字在创建后15分钟?

5 个答案:

答案 0 :(得分:6)

您刚回答了自己的问题 - 在名称中输入所有文件“expire”并在当前时间前15分钟修改并删除它们。

这是代码。它效率不高但很简单:

File dir=new File(".");
String []expiredFiles=dir.list(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return (name.contains("expired")&& new File(dir,name).lastModified()<System.currentTimeMillis()-15*60*1000);                
    }
});
for(String file:expiredFiles){
    new File(dir,file).delete();
}

您可以每15分钟左右运行一次。或者,更简单的方法,在每个请求被应答和关闭但是线程尚未停止时运行它。例如,在关闭响应对象上的输出流之后。它不需要太多资源,特别是当线程启动并仍在运行时。

答案 1 :(得分:2)

正如mlapeyre所说,在码头上没有这样的东西。请看Guavas cache

这样的东西会起作用,我想:

Cache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .removalListener(DELETE_FILES_LISTENER)
       .build();

答案 2 :(得分:0)

我认为码头没有内置功能。 您可以创建一种GarbageCollector类,并使用ScheduledExecutorService:

计划删除文件
Message: ...EndDate=2015-0005-13T06%3a00%3a00.00%2b0000...
Exception: System.FormatException: String was not recognized as a valid DateTime.
at System.DateTime.Parse(String s, IFormatProvider provider)
at System.Convert.ToDateTime(String value)

答案 3 :(得分:0)

创建一个模型类来存储有关上传图片的信息,例如imagePathuploadedTime

class UploadedImage {
    private Path imagePath;
    private long uploadedTime;
    public UploadedImage(Path imagePath, long uploadedTime) {
        this.imagePath = imagePath;
        this.uploadedTime = uploadedTime;
    }
    public Path getImagePath() {
        return imagePath;
    }
    public long getUploadedTime() {
        return uploadedTime;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final UploadedImage other = (UploadedImage) obj;
        if (!Objects.equals(this.imagePath, other.imagePath)) {
            return false;
        }
        if (this.uploadedTime != other.uploadedTime) {
            return false;
        }
        return true;
    }
}

为每个图像上传创建一个UploadedImage对象,并将它们存储在全局ArrayList中。

//...
ArrayList<UploadedImage> imageBucket = new ArrayList<>();
//...

public synchronized void uploadingImage(Path imagePath, long uploadedTime){         
     imageBucket.add(new UploadeImage(imagePath, uploadedTime));
}

准备一个线程来执行如下文件的删除。

    boolean deletionOff = false;
    new Thread(new Runnable() {
    private final long IMAGE_LIFE_TIME = 1000 * 60 * 15;//fifteen minutes
    @Override
    public void run() {
        while (!deletionOff) {
            //this fore-each will retrieve objects from OLDEST to NEWEST
            for (UploadedImage uploadedImage : imageBucket) {
                 //finds the elapsed time since the upload of this image
                long timeElapsed = System.currentTimeMillis() - uploadedImage.getUploadedTime();
                if (timeElapsed >= IMAGE_LIFE_TIME) {
                    //following commands will execute only if the image is eligible to delete
                    try {
                        Files.delete(uploadedImage.getImagePath());
                    } catch (IOException ex) {
                        //
                    } finally {
                        imageBucket.remove(uploadedImage);
                    }
                } else {
                    //this block will execute when IMAGE_LIFE_TIME is
                    //bigger than the elapsed time which means the
                    //selected image only have 
                    //(IMAGE_LIFE_TIME - timeElapsed) of time to stay alive 
                    //NOTE :
                    //there is no need to check the next UploadedImage
                    //objects as they were added to the list after the
                    //currently considering UploadedImage object, 
                    //which is still has some time to stay alive                           
                    try {
                        Thread.sleep(IMAGE_LIFE_TIME - timeElapsed);
                        break;
                    } catch (InterruptedException ex) {
                        //
                    }
                }
            }
        }
    }
}).start();

答案 4 :(得分:0)

我基本上使用cron触发器在我的网络服务器中设置了石英调度程序

并且工作看起来更像或像这样

public static void deleteFilesOlderThanNdays(int daysBack, String dirWay, org.apache.commons.logging.Log log) {

    File directory = new File(dirWay);
    if(directory.exists()){

        File[] listFiles = directory.listFiles();            
        long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
        for(File listFile : listFiles) {
            if(listFile.lastModified() < purgeTime) {
                if(!listFile.delete()) {
                    System.err.println("Unable to delete file: " + listFile);
                }
            }
        }
    } else {
        log.warn("Files were not deleted, directory " + dirWay + " does'nt exist!");
    }
}

REF:http://www.coderanch.com/t/384581/java/java/Delete-Files-Older-days