Back to Java
2026-02-086 min read

HTML Paragraphs (Java)

Learn HTML Paragraphs (Java) step by step with clear examples and exercises.

Title: HTML Paragraphs (Java)

Why This Matters

HTML paragraphs are fundamental building blocks of web development, allowing you to structure and format text on a webpage. In Java, we can manipulate HTML using libraries like Jsoup, making it easier to create dynamic content. Understanding how to work with HTML paragraphs is crucial for building interactive websites, handling user input, and debugging common issues that arise during development.

The Importance of Structured Content

Properly structured HTML content helps search engines understand the context of a webpage more easily, which can improve its ranking in search results. Additionally, well-structured HTML makes it easier for users to navigate and consume information on your website.

Prerequisites

  • Basic understanding of Java programming concepts such as variables, loops, and control structures
  • Familiarity with web development fundamentals (HTML, CSS, JavaScript)
  • Knowledge of Jsoup library for parsing HTML in Java
  • Understanding of basic file I/O operations in Java
  • Familiarity with Maven or Gradle build tools to manage dependencies

Java Basics and Web Development Fundamentals

Before diving into manipulating HTML paragraphs using Jsoup, it's essential to have a solid foundation in Java programming concepts as well as an understanding of web development fundamentals such as HTML, CSS, and JavaScript. Make sure you are comfortable with topics like variables, loops, control structures, classes, and objects before proceeding.

Core Concept

In Java, we can manipulate HTML paragraphs using the Jsoup library. Here's a step-by-step guide to creating, parsing, and modifying HTML paragraphs:

  1. Add Jsoup dependency to your project (Maven or Gradle)
  • Maven: org.jsoupjsoup1.14.3
  • Gradle: implementation 'org.jsoup:jsoup:1.14.3'
  1. Create a new Java file and import necessary libraries:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Selector;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
  1. Parse an HTML document containing paragraphs:
String html = "<html><body><p>This is a paragraph.</p><p>Another paragraph.</p></body></html>";
Document doc = Jsoup.parse(html);
  1. Access the first paragraph:
Element p1 = doc.select("p").get(0);
System.out.println(p1.text()); // This is a paragraph.
  1. Create a new HTML paragraph and add it to the document:
Element newPara = doc.createElement("p");
newPara.text("A new paragraph created in Java.");
doc.body().appendChild(newPara);
  1. Save the modified HTML back to a string or file:
String updatedHtml = doc.html();
System.out.println(updatedHtml); // Prints the updated HTML to console
Files.write(Paths.get("output.html"), updatedHtml.getBytes("UTF-8")); // Save to a file
  1. To modify an existing paragraph, you can change its text or other attributes:
p1.text("Modified paragraph.");
p1.attr("id", "my-paragraph");

Parsing HTML from Files and URLs

Jsoup allows you to parse HTML content from files as well as URLs. To parse an HTML file, pass the file path as a string argument to Jsoup's parse() method:

Document doc = Jsoup.parse("path/to/your/file.html");

To parse HTML from a URL, use Jsoup's connect() method and pass in the desired URL as an argument:

Document doc = Jsoup.connect("http://example.com").get();

Worked Example

Let's create a simple Java application that reads HTML content from a file, modifies the first paragraph, and saves the updated content back to a new file:

  1. Create an index.html file with some sample text:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample HTML</title>
</head>
<body>
<p id="first-para">This is the first paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
  1. Create a new Java file called HtmlParser.java and follow the core concept steps to read the HTML, modify the first paragraph, and save it back to a new file:
import org.jsoup.Jsoup;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

public class HtmlParser {
public static void main(String[] args) throws Exception {
String inputFilePath = "index.html";
String outputFilePath = "modified-index.html";

// Read HTML from file
byte[] htmlBytes = Files.readAllBytes(Paths.get(inputFilePath));
String html = new String(htmlBytes, "UTF-8");

// Parse the HTML document
Document doc = Jsoup.parse(html);

// Modify the first paragraph
Element p1 = doc.select("#first-para").get(0);
p1.text("Modified first paragraph.");

// Save the updated HTML back to a file
Files.write(Paths.get(outputFilePath), doc.html().getBytes("UTF-8"));
}
}

Common Mistakes

  1. Forgetting to import necessary libraries:
  • Solution: Make sure you have import org.jsoup.Jsoup; at the beginning of your Java file.
  1. Not properly parsing HTML from a file or URL:
  • Solution: Use Jsoup's parse() method and pass in the HTML content as a string, byte array, File object, or URL.
  1. Failing to select the correct HTML element using the wrong selector or incorrect index:
  • Solution: Double-check your CSS selector syntax and ensure you are accessing the correct element by its index or ID.
  1. Not handling exceptions when parsing HTML with Jsoup:
  • Solution: Use try-catch blocks to handle potential exceptions that may occur during parsing. For example:
try {
Document doc = Jsoup.connect("http://example.com").get();
} catch (IOException e) {
System.err.println("Error connecting to URL: " + e.getMessage());
}
  1. Not properly encoding the output HTML when saving it back to a file:
  • Solution: Use Files.write() with the "UTF-8" encoding to ensure that the saved HTML is correctly encoded and can be read by web browsers.

Practice Questions

  1. Write a Java program that reads an HTML file containing multiple paragraphs, adds a new paragraph at the beginning, and saves the updated content back to the same file.
  2. Given an HTML document with the following structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample HTML</title>
</head>
<body>
<p id="first-para">This is the first paragraph.</p>
<p>This is another paragraph.</p>
<p id="third-para">This is the third paragraph.</p>
</body>
</html>

Write a Java program that modifies the text of the second and third paragraphs, saves the updated content to a new file, and prints the modified HTML to the console.

FAQ

What is Jsoup?

  • Jsoup is a Java library for parsing HTML documents and extracting data from them.

Can I use Jsoup to manipulate CSS or JavaScript in an HTML document?

  • No, Jsoup only works with the structure of the HTML document itself. To manipulate CSS or JavaScript, you would need a different library or tool.

Is it possible to parse HTML from a URL using Jsoup?

  • Yes, you can pass a URL as an argument to Jsoup's parse() method to parse HTML content from the web.

How do I handle exceptions when parsing HTML with Jsoup?

  • Use try-catch blocks to handle potential exceptions that may occur during parsing. For example:
try {
Document doc = Jsoup.connect("http://example.com").get();
} catch (IOException e) {
System.err.println("Error connecting to URL: " + e.getMessage());
}

How do I properly encode the output HTML when saving it back to a file using Jsoup?

  • Use Files.write() with the "UTF-8" encoding to ensure that the saved HTML is correctly encoded and can be read by web browsers:
Files.write(Paths.get("output.html"), doc.html().getBytes("UTF-8"));
HTML Paragraphs (Java) | Java | XQA Learn