首页 / JAVA / java – 如果更新,只下载文件?
java – 如果更新,只下载文件?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 如果更新,只下载文件?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2117字,纯文字阅读大概需要4分钟。
内容图文
![java – 如果更新,只下载文件?](/upload/InfoBanner/zyjiaocheng/723/0e2605f06171447c96778a4271c5ad70.jpg)
我正在使用下面的代码下载文件.但是我只想下载如果远程文件比较新,那么本地存储(如果有的话).我可以以某种方式使用if-modefied-since http标头?如何更新我的代码以存档我的目标?
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mProgressDialog.dismiss();
// TODO: here file is downloaded and we are ready to process it.
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
我已经更新了我的代码看起来像这样……
@Override
protected String doInBackground(String... sUrl) {
long lastModified = new File(path).lastModified();
try
{
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
if(lastModified != 0)
{
connection.setIfModifiedSince(lastModified);
}
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
...
关于如何实际测试这个的任何好主意?如果文件不是更新的话,while循环不应该运行,对吗?
解决方法:
这正是那个标题的目的.您需要发出HTTP HEAD请求以获取标头,然后将标头中的时间戳与文件上最后修改的时间戳进行比较.如果服务器的副本较新,请发出GET以下载新副本.
内容总结
以上是互联网集市为您收集整理的java – 如果更新,只下载文件?全部内容,希望文章能够帮你解决java – 如果更新,只下载文件?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。