// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class EndianFun {
    private static final String FNM = "/work/data.dat";
    private static final byte[] DATA = { 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0 }; 
    private static final int DATALEN = DATA.length;
    private static void create() throws IOException {
        OutputStream os = new FileOutputStream(FNM);
        os.write(DATA);;
        os.close();
    }
    private static void readOld() throws IOException {
        InputStream is = new FileInputStream(FNM);
        DataInputStream dis = new DataInputStream(is);
        int n1 = dis.readInt();
        int n2 = dis.readInt();
        int n3 = dis.readInt();
        System.out.printf("old: %d %d %d\n", n1, n2, n3);
        dis.close();
        is.close();
    }
    private static void readRead(ByteOrder bo) throws IOException {
        FileInputStream fis = new FileInputStream(FNM);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = ByteBuffer.allocate(DATALEN);
        if(fc.read(bb) != DATALEN) { fc.close(); fis.close(); throw new RuntimeException("Bad number of bytes read"); };
        bb.order(bo);
        bb.flip();
        int n1 = bb.getInt();
        int n2 = bb.getInt();
        int n3 = bb.getInt();
        System.out.printf("read (%s): %d %d %d\n", bo, n1, n2, n3);
        fc.close();
        fis.close();
    }
    private static void readMapped(ByteOrder bo) throws IOException {
        FileInputStream fis = new FileInputStream(FNM);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = fc.map(MapMode.READ_ONLY, 0, DATALEN);
        bb.order(bo);
        int n1 = bb.getInt();
        int n2 = bb.getInt();
        int n3 = bb.getInt();
        System.out.printf("mapped (%s): %d %d %d\n", bo, n1, n2, n3);
        fc.close();
        fis.close();
    }
    public static void main(String[] args) throws IOException {
        create();
        readOld();
        readRead(ByteOrder.LITTLE_ENDIAN);
        readRead(ByteOrder.BIG_ENDIAN);
        readMapped(ByteOrder.LITTLE_ENDIAN);
        readMapped(ByteOrder.BIG_ENDIAN);
    }
}
