Why can't I write a PNG file correctly on Windows with Java from a downloaded source?
I'm trying to write a PNG file from a image retrieved from the web. This is what I'm doing (the http code and IOUtils magic are both from Apache):
public static void main(Stri开发者_如何学编程ng[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(new URI("http://tinyurl.com/krb43g"));
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
byte[] data = IOUtils.toByteArray(entity.getContent());
File tempFile = File.createTempFile("Picture", ".png");
Writer writer = new BufferedWriter(new FileWriter(tempFile));
IOUtils.write(data, writer);
writer.close();
Runtime.getRuntime().exec("rundll32.exe \"C:\\Program Files (x86)" +
"\\Windows Photo Viewer\\PhotoViewer.dll\", ImageView_Fullscreen "
+ tempFile.getAbsolutePath());
}
The image comes out corrupted in some way and Windows cannot display it. Am I doing something wrong with the write?
You're using a Writer when you should be using an OutputStream. Try replacing the lines that involve a Writer with the following:
OutputStream stream = new FileOutputStream(tempFile);
IOUtils.write(data, stream);
stream.close();
精彩评论