以下是我已经完成的代码,但我不确定它是否正确?任何人都在努力帮助please.Actually我想检查从服务器的文件的日期和保存在我的SD卡的文件,如果服务器的文件的日期更新,那么我必须下载并显示它,否则它将只是检查并显示SD卡中的文件。 提前谢谢。
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
public class FileChache {
File sdDir;
public FileChache(Activity activity)
{
// Find the directry to save cache image
//Gets the Android external storage directory.---> getExternalStorageState()
//MEDIA_MOUNTED if the media is present and mounted at its mount point with read/write access.
String sdState = android.os.Environment.getExternalStorageState();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
sdDir=new File(android.os.Environment.getExternalStorageDirectory(),"sash");
}
else
sdDir=activity.getCacheDir();
if(!sdDir.exists())
sdDir.mkdirs();
}
public File getFile(String url)
{
//identify images by hashcode
String filename= String.valueOf(url.hashCode());
System.out.println("The File name is:"+filename);
// Check whether the file is exist in SD Card
File f= new File(sdDir, filename);
System.out.println("The file date is:"+f.lastModified());
// Check whether the file is exist in SD Card
if(!f.exists())
{
return f;
}
else
{
//Check the last update of file
File file= new File(filename);
Date date= new Date(f.lastModified());
System.out.println("The last Modified of file is:"+date.toGMTString());
/*HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);*/
try
{
URL urll = new URL(url);
URLConnection conn= urll.openConnection();
String header=conn.getHeaderField("Last-Modified");
System.out.println("The header is:"+header);
Date ServerDate_timeStamp = new Date(header);
System.out.println("The headerDate is:"+ServerDate_timeStamp);
long filemodifiedDate= f.lastModified();
System.out.println("The last(Long) modified is:"+filemodifiedDate);
Date SD_cardFileModifiedDate = new Date(filemodifiedDate);
System.out.println("File file Modified Date Date is:"+ SD_cardFileModifiedDate);
if(!SD_cardFileModifiedDate.before(ServerDate_timeStamp))
{
File ff= new File(sdDir,filename);
return ff;
}
else
{
return f;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
return null;
}