从 Web 读取图像并写入 Java 中的文件

Read Image From Web And Write to File in Java

我试图从网页获取图像并写入文件,但最后我的照片查看器无法识别图片文件并且无法打开它(文件不可读)。

这是我的代码:

URL urlpic = new URL("https://static.asset.aparat.com/lp/16107806-6200-m.jpg");//示例图片 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());
}

你应该使用这样的东西:

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");
    }

在 windows10 上您不能使用根路径 (C:\) 来存储新文件。