Question: Write a Java program that downloads the first 100 comics of the webcomic XKCD. Be sure to use https:// for all URLS. This is the
Write a Java program that downloads the first 100 comics of the webcomic XKCD. Be sure to use https:// for all URLS.
This is the code I have so far..
package comics; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner;
public class Comics {
public static void main(String[] args) { try { System.out.println("In try"); for (int web = 1; web <=100; web++){ String protocol = "https"; String hostName = "xkcd.com"; String file = "/" + Integer.toString(web); URL url = new URL(protocol, hostName, file); Scanner sc = new Scanner(url.openStream()); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] words = line.split(">"); for (String word : words) { if (word.startsWith("Image URL (for hotlinking/embedding):")) { String imgURLstring = line.substring(61, line.length()); URL imgURL = new URL(imgURLstring); InputStream stream = imgURL.openStream(); Files.copy(stream, Paths.get("Comic" + Integer.toString(web) + ".png")); } } } while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } } } catch (Exception e) { System.err.println("Bad URL!"); e.printStackTrace(); } System.out.println("Done!"); } }
I need help downloading the first 100 comics from the website https://xkcd.com/1/, I think I am heading in the right direction however my code crashes and says I have a bad URL. Please help, and show output code!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
