我正在尝试从网上检索到的图像写入 PNG 文件。这就是我正在做的事情(http 代码和 IOUtils 魔法都来自 Apache):
public static void main(String[] 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());
}
图像以某种方式损坏,Windows 无法显示它。我写的有问题吗?
最佳答案
当您应该使用 OutputStream 时,您却使用了 Writer。尝试用以下内容替换涉及 Writer 的行:
OutputStream stream = new FileOutputStream(tempFile);
IOUtils.write(data, stream);
stream.close();
关于java - 为什么我无法在 Windows 上使用 Java 从下载的源正确写入 PNG 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3745596/