How do I read or download web page content?

You want to create a program that read a webpage content of a website page. The example below use the URL class to create a connection to the website. You create a new URL object and pass the URL information of a page. After the object created you can open a stream connection using the openStream() method of the URL object.

Next, you can read the stream using the BufferedReader object. This reader allows you to read line by line from the stream. To write it to a file create a writer using the BufferedWriter object and specify the file name where the downloaded page will be stored.

When all the content are read from the stream and stored in a file close the BufferedReader object and the BufferedWriter object at the end of your program.

package org.kodejava.net;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class UrlReadPageDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://kodejava.org");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
            BufferedWriter writer = new BufferedWriter(
                    new FileWriter("data.html", StandardCharsets.UTF_8));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                writer.write(line);
                writer.newLine();
            }

            reader.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I display message in browser status bar?

In this applet example you’ll see how to display a message in browser status bar. To make the example a bit more interesting we’ll display the current time as the message. The time will be updated every on second during the lifetime of the applet.

package org.kodejava.applet;

import java.applet.Applet;
import java.awt.Graphics;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeApplet extends Applet implements Runnable {
    private DateFormat formatter = null;
    private Thread t = null;

    public void init() {
        formatter = new SimpleDateFormat("hh:mm:ss");
        t = new Thread(this);
    }

    public void start() {
        t.start();
    }

    public void stop() {
        t = null;
    }

    public void paint(Graphics g) {
        Date now = Calendar.getInstance().getTime();
        // Show the current time on the browser status bar
        this.showStatus(formatter.format(now));
    }

    public void run() {
        int delay = 1000;
        try {
            while (t == Thread.currentThread()) {
                // Repaint the applet every on second
                repaint();
                Thread.sleep(delay);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Here is the html for our applet container.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Time Applet</title>
</head>

<body>
<applet
        code="org.kodejava.applet.TimeApplet"
        height="250"
        width="250">
</applet>
</body>
</html>
** Deprecated: The Applet API is deprecated since JDK 9, no replacement.

How do I remove duplicate element from array?

This example demonstrates you how to remove duplicate elements from an array using the help of java.util.HashSet class.

package org.kodejava.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayRemoveDuplicate {
    public static void main(String[] args) {
        // A string array with duplicate values.
        String[] data = {"A", "C", "B", "D", "A", "B", "E", "D", "B", "C"};
        System.out.println("Original array         : " + Arrays.toString(data));

        // Convert a string array into java.util.List because we need a list
        // object to create the java.util.Set object.
        List<String> list = Arrays.asList(data);

        // A set is a collection object that cannot have a duplicate values,
        // by converting the array to a set the duplicate value will be removed.
        Set<String> set = new HashSet<>(list);

        // Convert the java.util.Set back to array using the toArray() method of
        // the set object copy the value in the set to the defined array.
        String[] result = set.toArray(new String[0]);
        System.out.println("Array with no duplicate: " + Arrays.toString(result));
    }
}

The result of the code snippet above:

Original array         : [A, C, B, D, A, B, E, D, B, C]
Array with no duplicate: [A, B, C, D, E]

How do I convert Array to java.util.Set?

package org.kodejava.util;

import java.util.*;

public class ArrayToSetExample {
    public static void main(String[] args) {
        Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};

        // To convert an array into a java.util.Set firstly we need to convert the
        // array into a java.util.List using the Arrays.asList() method. With the
        // List object created we can instantiate a new java.util.HashSet and pass
        // the list as the constructor parameter.
        List<Integer> numberList = Arrays.asList(numbers);
        Set<Integer> numberSet = new HashSet<>(numberList);

        // Or we can simply combine the line above into single line.
        Set<Integer> anotherNumberSet = new HashSet<>(Arrays.asList(numbers));

        // Display what we get in the set using iterator.
        for (Iterator<Integer> iterator = numberSet.iterator(); iterator.hasNext(); ) {
            Integer number = iterator.next();
            System.out.print(number + ", ");
        }

        // Display what we get in the set using for-each.
        for (Integer number : anotherNumberSet) {
            System.out.print(number + ", ");
        }
    }
}

How do I use the HashMap class?

This example demonstrate you how to use the HashMap class to store values in a key-value structure. In this example we store a map of error codes with their corresponding description. To store a value into the map we use the put(key, value) method and to get it back we use the get(key) method. And we can also iterate the map using the available key sets of the map.

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, String> errors = new HashMap<>();

        // mapping some data in the map
        errors.put("404", "Resource not found");
        errors.put("403", "Access forbidden");
        errors.put("500", "General server error");

        // reading data from the map
        String errorDescription = errors.get("404");
        System.out.println("Error 404: " + errorDescription);

        // Iterating the map by the keys
        for (String key : errors.keySet()) {
            System.out.println("Error " + key + ": " + errors.get(key));
        }
    }
}

The result of the code snippet above:

Error 404: Resource not found
Error 500: General server error
Error 403: Access forbidden
Error 404: Resource not found