Downloaded images aren't viewable
So I have this code which downloads the source of an image and then writes it into a file.
It works fine, except for the fact that the created files aren't viewable. Using windows viewer, it gives me an "Image can't be constructed" error.
Code:
Code:
try {
URL URL = new URL(ImageLink);
HttpURLConnection huc = (HttpURLConnection)URL.openConnection();
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
huc.setRequestProperty("Pragma", "no-cache");
huc.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(huc.getInputStream()));
String line = null;
String source = "";
while ((line = reader.readLine()) != null) {
source += line; //Store the entire source of the image in a variable.
}
try {
Pattern p = Pattern.compile("/([\\d]*.[\\w]{2,4})$"); //Extract filename from the image URL
Matcher m = p.matcher(ImageLink);
m.find();
String filepath = "E:\\wamp\\www\\images\\" + m.group(1);
File file = new File(filepath); //Create a file at E:/wamp/www/images
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(source); //Write the downloaded source to the file.
out.close();
} catch (IOException e) {
System.err.println("General Exception " + e);
e.printStackTrace();
}
}
catch(IOException ioe) {
ioe.printStackTrace();
}
catch(Exception e) {
System.err.println("General Exception " + e);
e.printStackTrace();
}
}
Can anyone tell me what I'm doing wrong?
Thanks.