Web Page Read Quiz - Java Network

Java examples for Network:URL

Introduction

Write an application that stores web pages on your computer so that you can read them while you are not connected to the Internet.

Demo Code

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {

  public static void main(String[] arguments)throws MalformedURLException  {

    try {// w  w w . j  ava  2s.c  o m
      URL   page = new URL("https://java2s.com");

      // Create file object
      String filename = page.getHost() + "_" + page.getFile() + "_file.html";
      File output = new File(filename);
      try {
        FileWriter fw = new FileWriter(output);
        BufferedWriter out = new BufferedWriter(fw);

        HttpURLConnection conn = (HttpURLConnection) page.openConnection();
        conn.connect();
        InputStreamReader in = new InputStreamReader(
            (InputStream) conn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line;
        do {
          line = buff.readLine();
          if (line != null) {
            out.write(line, 0, line.length());
          }
        } while (line != null);
        out.flush();
        out.close();
        System.out.println(output.getName() + " saved");
      } catch (IOException ioe) {
        System.out.println("IO Error:" + ioe.getMessage());
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();;
    }
  }
}

Result


Related Tutorials