Java File Write via ByteBuffer writeUtf8(DataOutput out, String string)

Here you can find the source of writeUtf8(DataOutput out, String string)

Description

Safely writes a string in UTF-8 to a byte stream.

License

LGPL

Parameter

Parameter Description
out The stream
string The string or null

Exception

Parameter Description
IOException In case of a writing or encoding error

Declaration

public static void writeUtf8(DataOutput out, String string) throws IOException 

Method Source Code

//package com.java2s;
/**/*www  .  ja v  a 2s.c  o  m*/
 * Copyright 2009-2016 Three Crickets LLC.
 * <p>
 * The contents of this file are subject to the terms of the LGPL version 3.0:
 * http://www.gnu.org/copyleft/lesser.html
 * <p>
 * Alternatively, you can obtain a royalty free commercial license with less
 * limitations, transferable or non-transferable, directly from Three Crickets
 * at http://threecrickets.com/
 */

import java.io.DataOutput;

import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {
    /**
     * UTF-8 charset.
     */
    private static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * Safely writes a string in UTF-8 to a byte stream. This method does not
     * differentiate between empty strings and nulls.
     * <p>
     * Unlike {@link DataOutput#writeUTF(String)}, this implementation does not
     * limit the string size.
     * 
     * @param out
     *        The stream
     * @param string
     *        The string or null
     * @throws IOException
     *         In case of a writing or encoding error
     * @see #readUtf8(DataInput)
     * @see #encodeUtf8(String)
     */
    public static void writeUtf8(DataOutput out, String string) throws IOException {
        if (string == null)
            out.writeInt(0);
        else {
            byte[] bytes = encodeUtf8(string);
            out.writeInt(bytes.length);
            out.write(bytes);
        }
    }

    /**
     * Safely decodes a string as UTF-8.
     * 
     * @param string
     *        The string
     * @return The bytes
     */
    public static byte[] encodeUtf8(String string) {
        ByteBuffer buffer = UTF8.encode(string);
        byte[] bytes;
        if (buffer.hasArray())
            bytes = buffer.array();
        else {
            buffer.clear();
            bytes = new byte[buffer.capacity()];
            buffer.get(bytes);
        }
        return bytes;
    }
}

Related

  1. writeString(ByteArrayOutputStream bout, String val)
  2. writeStringContents(String contents, WritableByteChannel channel)
  3. writeStringData(DataOutputStream mDataOutputStream, String token)
  4. writeStringToSocketChannel(String text, SocketChannel sc)
  5. writeToFile(String path, ByteOrder byteOrder)
  6. writeVector(DataOutputStream output, float[] vector)
  7. writeWaveFile44100_16Bit_Mono(short[] data, File file)