开发者

How do you obtain modified date from a remote file (Java)?

开发者 https://www.devze.com 2022-12-22 23:35 出处:网络
I\'ve a function to download a file from a remote URL (using Java). Now I want to know the real modified date, because when I download it I lost this info. Thanks in advance.

I've a function to download a file from a remote URL (using Java). Now I want to know the real modified date, because when I download it I lost this info. Thanks in advance.

public void downloadFile(String remoteFile, String localFile)
        throws IOException {
    BufferedInputStream in;
    try {
        URL url = new URL(remoteFile);


        in = new BufferedInputStream(url.openStream());
        FileOutputStream fos = new 开发者_Python百科FileOutputStream(localFile);
        BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
        byte data[] = new byte[1024];
        int count = 0;
        while ((count = in.read(data, 0, 1024)) > 0) {
            bout.write(data, 0, count);
        }
        bout.close();
        in.close();
        log.write(remoteFile + " - Download Successful.");
        //System.out.println(remoteFile + " - Download Successful.");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        log.write("The file " + remoteFile + " doesn't exist.");
        //System.out.println("The file " + remoteFile + " doesn't exist.");
    }
}


Any decent webserver will put this information in the Last-Modified response header. You can obtain it by URLConnection#getLastModified(). Here's an example:

URLConnection connection = new URL("https://cdn.sstatic.net/Img/unified/sprites.svg").openConnection();
long lastModified = connection.getLastModified();
System.out.println(lastModified); // 1649805134000

You can then easily convert it the desired date type. E.g. Instant:

Instant instant = Instant.ofEpochMilli(lastModified);
System.out.println(instant); // 2022-04-12T23:12:14Z

Or the legacy java.util.Date:

Date date = new Date(lastModified);
System.out.println(date); // Tue Apr 12 19:12:14 AST 2022


Zip the folder with your files before downloading, then download the zip folder and unzip it there. This will preserve the modified and created dates. I don't know if this answer is in your context.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号