Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;

import java.io.OutputStream;

public class Main {
    public static void writeWLenData(OutputStream os, byte[] bytes, boolean big_endian) throws IOException {
        if (bytes == null) {
            writeShort(os, 0, big_endian);
        } else {
            writeShort(os, bytes.length, big_endian);
            os.write(bytes);
        }
    }

    public static void writeShort(OutputStream out, int s) throws IOException {
        byte[] buffer = new byte[] { (byte) ((s >> 8) & 0xff), (byte) (s & 0xff) };

        out.write(buffer);
        out.flush();
        buffer = null;

    }

    public static void writeShort(OutputStream out, int s, boolean big_endian) throws IOException {
        writeNumber(out, s, 2, big_endian);
    }

    public static void writeNumber(OutputStream out, long s, int len, boolean big_endian) throws IOException {
        if (len <= 0 || len > 8)
            throw new IllegalArgumentException("length must between 1 and 8.");

        byte[] buffer = numberToBytes(s, len, big_endian);
        out.write(buffer);
        out.flush();
    }

    public static byte[] numberToBytes(long s, int len, boolean big_endian) {
        byte[] buffer = new byte[len];
        int start = big_endian ? (len - 1) : 0;
        int end = big_endian ? -1 : len;
        int inc = big_endian ? -1 : 1;

        for (int i = start; i != end; i += inc) {
            buffer[i] = (byte) (s & 0xff);
            s >>>= 8;
        }

        return buffer;
    }
}