/** * Download image
* @param imageurl remote image url
* @param localpath your sd card path
* @return file object
*/
private File getPath(String imageurl, String localpath) {
String filepath = null;
File file = null;
InputStream inputStream = null;
try {
URL url = new URL(imageurl);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(20000);
try {
urlConnection.connect();
inputStream = urlConnection.getInputStream();
} catch (SocketTimeoutException e) {
return file;
} catch (Exception e) {
return file;
}
if (localpath != null) {
file = new File(localpath);
FileOutputStream fileOutput = new FileOutputStream(
file);
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
if (inputStream != null) {
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength; }
}
fileOutput.close();
}
} catch (Exception e) {
e.printStackTrace();
Log.i("ImageDownload", "Exception in DownloadRunnable" + e);
}
Log.i("filepath:", " " + filepath);
return file;
}