Java SwappedDataInputStream-class And Method Code Example


Here is an example of how you might use the SwappedDataInputStream class from the org.apache.commons.io package in Java:

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import org.apache.commons.io.input.SwappedDataInputStream;

public class MyClass {

    public void doSomethingWithSwappedDataInputStream() throws Exception {
        // Create a byte array input stream
        byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8};
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        
        // Create a data input stream
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        
        // Create a swapped data input stream
        SwappedDataInputStream swappedDataInputStream = new SwappedDataInputStream(dataInputStream);

        // Read an int value from the stream
        int value = swappedDataInputStream.readInt();
        System.out.println(value);
    }
}

The SwappedDataInputStream class is a DataInputStream which allows to read data in the opposite byte order than that used by the underlying stream. In this example, we create a ByteArrayInputStream and passed it to the DataInputStream constructor and then passed that to SwappedDataInputStream constructor, it will read the data in the opposite byte order than that used by the underlying stream.

The SwappedDataInputStream class has similar methods as DataInputStream, such as readBoolean(), readByte(), readChar(), readDouble(), readFloat(), readLong(), readShort(), etc.

It is important to close the SwappedDataInputStream after you are done with it to release the resources associated with the underlying stream.