How do I split up string using regular expression?

This code snippet uses the java.util.regex.Pattern.split() method to split-up input string separated by commas or whitespaces (spaces, tabs, new lines, carriage returns, form feeds).

package org.kodejava.regex;

import java.util.regex.Pattern;

public class RegexSplitExample {
    public static void main(String[] args) {
        // Pattern for finding commas, whitespaces (spaces, tabs, new lines,
        // carriage returns, form feeds).
        String pattern = "[,\\s]+";
        String colors = """
                Red,White, Blue   Green        Yellow,
                Orange Pink""";

        Pattern splitter = Pattern.compile(pattern);
        String[] results = splitter.split(colors);

        for (String color : results) {
            System.out.format("Color = \"%s\"%n", color);
        }
    }
}

The result of our code snippet is:

Color = "Red"
Color = "White"
Color = "Blue"
Color = "Green"
Color = "Yellow"
Color = "Orange"
Color = "Pink"

How do I read CLOBs data from database?

package org.kodejava.jdbc;

import java.io.File;
import java.io.FileWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.*;

public class ClobReadDemo {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection conn =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            String sql = "SELECT book_id, data FROM book_excerpt";
            PreparedStatement stmt = conn.prepareStatement(sql);

            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                long bookId = resultSet.getLong("book_id");
                // Get the character stream of our CLOB file
                Reader reader = resultSet.getCharacterStream("data");

                File file = new File(bookId + ".txt");
                try (FileWriter writer = new FileWriter(file, StandardCharsets.UTF_8)) {
                    char[] buffer = new char[1];
                    while (reader.read(buffer) > 0) {
                        writer.write(buffer);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The structure of book_excerpt table.

CREATE TABLE `book_excerpt`
(
    `id`          bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `book_id`     bigint(20) unsigned NOT NULL,
    `description` varchar(255)        NOT NULL,
    `data`        longtext,
    PRIMARY KEY (`id`),
    CONSTRAINT `book_excerpt_ibfk_1` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`)
) ENGINE = InnoDB;

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I store CLOBs data into database?

package org.kodejava.jdbc;

import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ClobInsertDemo {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection conn =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            conn.setAutoCommit(false);

            String sql = "INSERT INTO book_excerpt " +
                         "(book_id, description, data) VALUES (?, ?, ?)";

            File data = new File("java-8-in-action.txt");
            try (PreparedStatement stmt = conn.prepareStatement(sql);
                 FileReader reader = new FileReader(data)) {

                stmt.setLong(1, 1L);
                stmt.setString(2, "Java 8 in Action");
                stmt.setCharacterStream(3, reader, (int) data.length());
                stmt.execute();

                conn.commit();
            } catch (Exception e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The structure of book_excerpt table.

CREATE TABLE `book_excerpt`
(
    `id`          bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `book_id`     bigint(20) unsigned NOT NULL,
    `description` varchar(255)        NOT NULL,
    `data`        longtext,
    PRIMARY KEY (`id`),
    CONSTRAINT `book_excerpt_ibfk_1` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`)
) ENGINE = InnoDB;

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I read BLOBs data from database?

This example shows you how to read BLOBs data from database table.

package org.kodejava.jdbc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;

public class BlobReadDemo {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection conn =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            String sql = "SELECT name, image FROM product_image";

            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                String name = rs.getString("name");

                File image = new File(name);
                try (FileOutputStream fos = new FileOutputStream(image)) {
                    byte[] buffer = new byte[1024];

                    // Get the binary stream of our BLOB data
                    InputStream is = rs.getBinaryStream("image");
                    while (is.read(buffer) > 0) {
                        fos.write(buffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Table structure of product_image

CREATE TABLE `product_image`
(
    `id`          bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `product_id`  bigint(20) unsigned NOT NULL,
    `name`        varchar(255)        NOT NULL,
    `description` varchar(255) DEFAULT NULL,
    `image`       blob,
    PRIMARY KEY (`id`),
    KEY `product_id` (`product_id`),
    CONSTRAINT `product_image_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
) ENGINE = InnoDB;

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central