Java 怎么从servletcontext中检索路径上次修改的内容

2019年8月17日22:04:01 评论 25

1.简介

Java 怎么从servletcontext中检索路径上次修改的内容?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletContext;

public class Main{
    
    public final static long retrieveLastModifiedByPath(
            ServletContext servletContext, ClassLoader classLoader,
            String path) {
        if (path.startsWith("file:")) {
            try {
                URL url = new URL(path);
                return retrieveLastModifiedFromURL(url);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
        } else if (path.startsWith("classpath:")) {
            String cls = path.substring("classpath:".length());
            if (cls.startsWith("/")) {
                cls = cls.substring(1);
            }
            return retrieveLastModifiedFromURL(classLoader.getResource(cls));
        } else {
            try {
                return retrieveLastModifiedFromURL(servletContext
                        .getResource(path));
            } catch (MalformedURLException e) {
                return 0L;
            }
        }
    }
    private final static long retrieveLastModifiedFromURL(URL url) {
        try {
            URLConnection con = url.openConnection();
            try {
                return con.getLastModified();
            } catch (Exception ex) {
                return 0L;
            } finally {
                con.getInputStream().close();
            }
        } catch (IOException e) {
            return 0L;
        }
    }
}

 

3.总结

示例代码演示了 Java 怎么从servletcontext中检索路径上次修改的内容,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: