如何从远程文件(Java)中获取修改日期? [英] How do you obtain modified date from a remote file (Java)?
本文介绍了如何从远程文件(Java)中获取修改日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从远程 URL 下载文件的功能(使用 Java).现在我想知道真正的修改日期,因为当我下载它时我丢失了这些信息.提前致谢.
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.");
}
}
推荐答案
任何体面的网络服务器都会将此信息放在 Last-Modified
响应标头.您可以通过 URLConnection#getHeaderField()
.举个例子
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);
截至目前打印
Sun, 17 Jan 2010 18:29:31 GMT
这很容易使用 Date 对象rel="noreferrer">SimpleDateFormat
:
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);
这篇关于如何从远程文件(Java)中获取修改日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文