How do I use DataInputStream and DataOutputStream?

java.io.DataOutputStream and java.io.DataInputStream give us the power to write and read primitive data type to a media such as file. Both of these classes have the corresponding methods to write primitive data type and to read it back.

Using this class make it easier to read int, float, double data and others without needing to interpret if the data should be an int or a float data. Let’s see our code below.

package org.kodejava.io;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class PrimitiveStreamExample {

    public static void main(String[] args) {
        // Prepares some data to be written to a file.
        int cityIdA = 1;
        String cityNameA = "Green Lake City";
        int cityPopulationA = 500000;
        float cityTempA = 15.50f;

        int cityIdB = 2;
        String cityNameB = "Salt Lake City";
        int cityPopulationB = 250000;
        float cityTempB = 10.45f;

        /*
        Create an instance of FileOutputStream with cities.dat as the file
        name to be created. Then we pass the input stream object in the
        DataOutputStream constructor.
        */
        try (FileOutputStream fos = new FileOutputStream("cities.dat");
             DataOutputStream dos = new DataOutputStream(fos)) {

            /*
             Below we write some data to the cities.dat. DataOutputStream
             class have various method that allow us to write primitive type
             data and string. There are method called writeInt(),
             writeFloat(), writeUTF(), etc.
            */
            dos.writeInt(cityIdA);
            dos.writeUTF(cityNameA);
            dos.writeInt(cityPopulationA);
            dos.writeFloat(cityTempA);

            dos.writeInt(cityIdB);
            dos.writeUTF(cityNameB);
            dos.writeInt(cityPopulationB);
            dos.writeFloat(cityTempB);
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*
         Now we have a cities.dat file with some data in it. Next you'll see
         how easily we can read back this data and display it. Just like the
         DataOutputStream the DataInputStream class have the corresponding
         read methods to read data from the file. Some method names
         are readInt(), readFloat(), readUTF(), etc.
        */
        try (FileInputStream fis = new FileInputStream("cities.dat");
             DataInputStream dis = new DataInputStream(fis)) {

            // Read the first data
            int cityId1 = dis.readInt();
            String cityName1 = dis.readUTF();
            int cityPopulation1 = dis.readInt();
            float cityTemperature1 = dis.readFloat();

            printOut(cityId1, cityName1, cityPopulation1, cityTemperature1);

            // Read the second data
            int cityId2 = dis.readInt();
            String cityName2 = dis.readUTF();
            int cityPopulation2 = dis.readInt();
            float cityTemperature2 = dis.readFloat();

            printOut(cityId2, cityName2, cityPopulation2, cityTemperature2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printOut(int cityId1, String cityName1, int cityPopulation1, float cityTemperature1) {
        System.out.println("Id: " + cityId1);
        System.out.println("Name: " + cityName1);
        System.out.println("Population: " + cityPopulation1);
        System.out.println("Temperature: " + cityTemperature1);
    }
}

The generated result of our program are:

Id: 1
Name: Green Lake City
Population: 500000
Temperature: 15.5
Id: 2
Name: Salt Lake City
Population: 250000
Temperature: 10.45

How do I use RandomAccessFile class?

This is an example of using RandomAccessFile class to read and write data to a file. Using RandomAccessFile enable us to read or write to a specific location in the file at the file pointer. Imagine the file as a large array of data that have their own index.

In the code below you’ll see how to create an instance of RandomAccessFile and define its operation mode (read or write). After we create an object we write some data, some book’s titles to the file. The last few line of the codes demonstrate how to read file data.

package org.kodejava.io;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileExample {

    public static void main(String[] args) {
        try {
            // Let's write some book's title to the end of the file
            String[] books = new String[5];
            books[0] = "Professional JSP";
            books[1] = "The Java Application Programming Interface";
            books[2] = "Java Security";
            books[3] = "Java Security Handbook";
            books[4] = "Hacking Exposed J2EE & Java";

            // Create a new instance of RandomAccessFile class. We'll do a "r"
            // read and "w" write operation to the file. If you want to do a write
            // operation you must also allow read operation to the RandomAccessFile
            // instance.
            RandomAccessFile raf = new RandomAccessFile("books.dat", "rw");
            for (String book : books) {
                raf.writeUTF(book);
            }

            // Write another data at the end of the file.
            raf.seek(raf.length());
            raf.writeUTF("Servlet & JSP Programming");

            // Move the file pointer to the beginning of the file
            raf.seek(0);

            // While the file pointer is less than the file length, read the
            // next strings of data file from the current position of the
            // file pointer.
            while (raf.getFilePointer() < raf.length()) {
                System.out.println(raf.readUTF());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result of our program are:

Professional JSP
The Java Application Programming Interface
Java Security
Java Security Handbook
Hacking Exposed J2EE & Java
Servlet & JSP Programming

How do I create a directories recursively?

The code below use File.mkdirs() method to create a collection of directories recursively. It will create a directory with all its necessary parent directories.

package org.kodejava.io;

import java.io.File;

public class CreateDirs {
    public static void main(String[] args) {
        // Define a deep directory structures and create all the
        // directories at once.
        String directories = "D:/kodejava/a/b/c/d/e/f/g/h/i";
        File file = new File(directories);

        // The mkdirs will create folder including any necessary
        // but nonexistence parent directories. This method returns
        // true if and only if the directory was created along with
        // all necessary parent directories.
        boolean created = file.mkdirs();
        System.out.println("Directories created? " + created);
    }
}

How do I compare string regardless of their case?

Here is an example of comparing two strings for equality without considering their case sensitivity. To do this we can use equalsIgnoreCase() method of the String class. Let’s see an example below:

package org.kodejava.basic;

public class EqualsIgnoreCase {
    public static void main(String[] args) {
        String uppercase = "ABCDEFGHI";
        String mixed = "aBCdEFghI";

        // To compare two string equality regarding it case use the
        // String.equalsIgnoreCase method.
        if (uppercase.equalsIgnoreCase(mixed)) {
            System.out.println("Uppercase and Mixed equals.");
        }
    }
}

How do I insert a string in the StringBuilder?

package org.kodejava.lang;

public class StringBuilderInsert {
    public static void main(String[] args) {
        StringBuilder alphabets = new StringBuilder("abcdfghopqrstuvwxyz");
        System.out.println("alphabets = " + alphabets);

        //  |a|b|c|d|f|g|h|i|....
        //  0|1|2|3|4|5|6|7|8|...
        //
        // From the above sequence you can see that the index of the string is
        // started from 0, so when we insert a string in the fourth offset it
        // means it will be inserted after the "d" letter. There are other overload
        // version of this method that can be used to insert other type of data
        // such as char, int, long, float, double, Object, etc.
        alphabets.insert(4, "e");
        System.out.println("alphabets = " + alphabets);

        // Here we insert an array of characters to the StringBuilder.
        alphabets.insert(8, new char[] {'i', 'j', 'k', 'l', 'm', 'n'});
        System.out.println("alphabets = " + alphabets);
    }
}

The result of the code snippet above:

alphabets = abcdfghopqrstuvwxyz
alphabets = abcdefghopqrstuvwxyz
alphabets = abcdefghijklmnopqrstuvwxyz