How do you obtain modified date from a remote file

2019-04-02 09:22发布

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 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.");
    }
}

标签: java stream
2条回答
闹够了就滚
2楼-- · 2019-04-02 09:46

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

URLConnection connection = new URL("http://sstatic.net/so/img/logo.png").openConnection();
String lastModified = connection.getHeaderField("Last-Modified");
System.out.println(lastModified);

which prints as of now

Sun, 17 Jan 2010 18:29:31 GMT

This is easy convertable to a Date object using SimpleDateFormat:

Date date = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).parse(lastModified);
查看更多
霸刀☆藐视天下
3楼-- · 2019-04-02 09:51

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.

查看更多
登录 后发表回答