用Java写一个爬取图片的代码
时间: 2023-04-04 07:01:42 浏览: 49
你好,以下是Java爬取图片的代码示例:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class ImageCrawler {
public static void main(String[] args) throws Exception {
String imageUrl = "https://www.example.com/image.jpg"; // 图片地址
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
FileOutputStream out = new FileOutputStream("image.jpg"); // 保存图片的文件名
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, , len);
}
out.close();
in.close();
System.out.println("图片下载完成!");
}
}
希望对你有帮助。