How do I delete directory recursively?

Using the FileUtils.deleteDirectory() from the Apache Commons IO library, we can simplify the process of deleting directory and everything below it recursively.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class DeleteDirectory {
    public static void main(String[] args) {
        try {
            File directory = new File("F:/Temp");

            // Deletes a directory recursively. When a deletion process is failed, an
            // IOException will be thrown; that's why we catch the exception.
            FileUtils.deleteDirectory(directory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

How do I create a human-readable file size?

This example demonstrates how to create a human-readable file size using the FileUtils class of the Apache Commons IO library. The byteCountToDisplaySize() method take the file size in bytes and return a human-readable display of the file size in bytes, kilobytes, megabytes, gigabytes, etc.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;

public class ReadableFileSize {
    public static void main(String[] args) {
        File file = new File("D:/Downloads/jdk-17_windows-x64_bin.exe");

        long size = file.length();
        String display = FileUtils.byteCountToDisplaySize(size);

        System.out.println("Name    = " + file.getName());
        System.out.println("Size    = " + size);
        System.out.println("Display = " + display);
    }
}

Here are the results of our program:

Name    = jdk-17_windows-x64_bin.exe
Size    = 159373640
Display = 151 MB

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

How do I read an XML document using JDOM?

This example provide a small code snippet on how to use JDOM to parse an XML document, iterates each of the element and read the element or attributes values. To play with this example you have to have the JDOM library. You can download it from JDOM website.

package org.kodejava.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ReadXmlDocument {
    public static void main(String[] args) {
        // Our imaginary xml file to be processed in this example.
        String data = """
                <root>
                    <row>
                        <column name="username" length="16">admin</column>
                        <column name="password" length="128">secret</column>
                    </row>
                    <row>
                        <column name="username" length="16">jdoe</column>
                        <column name="password" length="128">password</column>
                    </row>
                </root>""";

        // Create an instance of SAXBuilder
        SAXBuilder builder = new SAXBuilder();
        try {
            // Tell the SAXBuilder to build the Document object from the
            // InputStream supplied.
            Document document = builder.build(
                    new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)));

            // Get our xml document root element which equals to the
            // <root> tag in the xml document.
            Element root = document.getRootElement();

            // Get all the children named with <row> in the document.
            // The method return the children as a java.util.List
            // object.
            List<Element> rows = root.getChildren("row");
            for (Element row : rows) {
                // Convert each row to an Element object and get its
                // children which will return a collection of <column>
                // elements. When we have to column row we can read
                // the attribute value (name, length) as defined above
                // and also read its value (between the <column></column>
                // tag) by calling the getText() method.
                //
                // The getAttribute() method also provide a handy method
                // if we want to convert the attribute value to a correct
                // org.kodejava.data type, in the example we read the length attribute
                // value as an integer.
                List<Element> columns = row.getChildren("column");
                for (Element column : columns) {
                    String name = column.getAttribute("name").getValue();
                    String value = column.getText();
                    int length = column.getAttribute("length").getIntValue();

                    System.out.println("name = " + name);
                    System.out.println("value = " + value);
                    System.out.println("length = " + length);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

How do I determine bean’s property type?

Using the PropertyUtils.getPropertyType() we can determine the bean property type. This method return a Class object of bean’s property type.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Record;

public class PropertyType {
    public static void main(String[] args) {
        Record record = new Record();
        record.setTitle("Magical Mystery Tour");

        try {
            /*
             * Using PropertyUtils.getPropertyType() to determine the type of
             * title property.
             */
            Class<?> type = PropertyUtils.getPropertyType(record, "title");
            System.out.println("type = " + type.getName());

            String value = (String) PropertyUtils.getProperty(record, "title");
            System.out.println("value = " + value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.commons.beanutils.support;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Record {
    private Long id;
    private String title;
    private List<Track> tracks = new ArrayList<>();
    private Map<String, Track> mapTracks = new HashMap<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<Track> getTracks() {
        return tracks;
    }

    public void setTracks(List<Track> tracks) {
        this.tracks = tracks;
    }

    public void setMapTracks(Map<String, Track> mapTracks) {
        this.mapTracks = mapTracks;
    }

    public Map<String, Track> getMapTracks() {
        return mapTracks;
    }
}

The output of the code snippet above:

type = java.lang.String
value = Magical Mystery Tour

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I read mapped bean’s property value?

In this example you’ll see how to read mapped property value of a bean. We use PropertyUtils.getMappedProperty() method the read the mapped property of the Record object that consist of Track objects.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;
import org.kodejava.commons.beanutils.support.Record;

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

public class ReadMapProperty {
    public static void main(String[] args) {
        Record record = new Record();
        record.setTitle("Abbey Road");

        Track track1 = new Track();
        track1.setTitle("Come Together");

        Track track2 = new Track();
        track2.setTitle("Something");

        Map<String, Track> tracks = new HashMap<>();
        tracks.put("1", track1);
        tracks.put("2", track2);

        record.setMapTracks(tracks);

        try {
            Track track = (Track) PropertyUtils.getMappedProperty(record, "mapTracks(1)");
            System.out.println("track.getTitle() = " + track.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.commons.beanutils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Record {
    private Long id;
    private String title;
    private List<Track> tracks = new ArrayList<>();
    private Map<String, Track> mapTracks = new HashMap<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<Track> getTracks() {
        return tracks;
    }

    public void setTracks(List<Track> tracks) {
        this.tracks = tracks;
    }

    public void setMapTracks(Map<String, Track> mapTracks) {
        this.mapTracks = mapTracks;
    }

    public Map<String, Track> getMapTracks() {
        return mapTracks;
    }
}

And here is the result of our program.

track.getTitle() = Come Together

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central