Java DataOutput Write String writeString(final String data, final DataOutput out, final int length)

Here you can find the source of writeString(final String data, final DataOutput out, final int length)

Description

write String

License

Open Source License

Declaration

public static void writeString(final String data, final DataOutput out, final int length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.DataOutput;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class Main {
    /**//  w  w w .  j a va2s  .c o  m
     * @param data        the String to translate
     * @param length      the length (number of bytes) to write
     * @param destination the array to write to
     * @param offset      location where highest byte goes
     * @return the number of bytes written
     */
    public static int writeString(final String data, final int length, final byte[] destination, int offset) {
        requireDestinationLength(destination, offset, length);
        byte[] src;
        try {
            src = data.getBytes("UTF-8");
        } catch (UnsupportedEncodingException uee) {
            System.err.println(uee + "\nSwitching to default encoding");
            src = data.getBytes();
        }
        for (int i = 0; i < length; ++i) {
            destination[offset + i] = i < src.length - 1 ? src[i] : 0;
        }
        return length;
    }

    public static void writeString(final String data, final DataOutput out, final int length) {
        try {
            byte[] bytes = data.getBytes("UTF-8");
            assert bytes.length <= length;
            out.write(bytes);
            if (bytes.length < length)
                out.write(new byte[length - bytes.length]); //pad
        } catch (IOException ioe) {
            throw new Error(ioe);
        }
    }

    /**
     * Helper method to check the Contract precondition of write methods
     */
    private static void requireDestinationLength(final byte[] destination, final int offset, final int length) {
        if (destination.length < offset + length - 1) {
            throw new IllegalArgumentException("Not enough room available in destination array:\n have "
                    + destination.length + " bytes, need " + (offset + length));
        }
    }
}

Related

  1. writeString(DataOutput out, String s)
  2. writeString(DataOutput out, String s)
  3. writeString(DataOutput out, String s)
  4. writeString(DataOutput out, String v)
  5. writeString(DataOutput output, String s)
  6. writeString(final String string, final DataOutput out)
  7. writeString(String par0Str, DataOutput par1DataOutput)
  8. writeString(String s, DataOutput output)
  9. writeString(String s, DataOutput stream)