我试图从网页上获取图像并写入文件。但最后我的照片查看器无法识别图片文件并且无法打开它(文件无法读取)。
这是我的代码:
URL urlpic=new URL("https://static.asset.aparat.com/lp/16107806-6200-m.jpg");//sample pic url
HttpURLConnection connectionToPicFile=(HttpURLConnection)urlpic.openConnection();
BufferedReader buffPic=new BufferedReader(new InputStreamReader(connectionToPicFile.getInputStream()));
String pic="";
String alldatapic="";
while((pic=buffPic.readLine())!=null)
{
alldatapic+=pic;
}
try
{
FileOutputStream fout=new FileOutputStream("D://pic.jpg");//where i want the file to be saved
byte[] b=alldatapic.getBytes();
fout.write(b);
fout.close();
}
catch(Exception ex)
{
System.out.println(ex.toString()+" "+ex.getMessage());
}
答案 0 :(得分:1)
你应该使用这样的东西:
BufferedImage image = null;
try {
URL url = new URL("https://static.asset.aparat.com/lp/16107806-6200-m.jpg");
image = ImageIO.read(url);
ImageIO.write(image, "jpg", new File("E:\\out.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
在Windows 10上,您无法使用根路径(C:\)来存储新文件。