public class FileUtil {
public static boolean saveImageToDisk(String imgUrl, String fileName, String filePath) {
InputStream inputStream = null;
inputStream = getInputStream(imgUrl);
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath + fileName);
while ((len = inputStream.read(data))!=-1) {
fileOutputStream.write(data,0,len);
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally{
if(fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static InputStream getInputStream(String imgUrl){
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(imgUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
inputStream = httpURLConnection.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}