我有一个从远程 URL 下载文件的功能(使用 Java)。现在我想知道真正的修改日期,因为当我下载它时我丢失了此信息。提前致谢。
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.");
}
}
任何像样的网络服务器都会将此信息放在Last-Modified http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29响应头。您可以通过以下方式获取它URLConnection#getLastModified() https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/net/URLConnection.html#getLastModified()。这是一个例子:
URLConnection connection = new URL("https://cdn.sstatic.net/Img/unified/sprites.svg").openConnection();
long lastModified = connection.getLastModified();
System.out.println(lastModified); // 1649805134000
然后您可以轻松地将其转换为所需的日期类型。例如。Instant
:
Instant instant = Instant.ofEpochMilli(lastModified);
System.out.println(instant); // 2022-04-12T23:12:14Z
或者遗产java.util.Date
:
Date date = new Date(lastModified);
System.out.println(date); // Tue Apr 12 19:12:14 AST 2022
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)