Java DataOutput Write String writeString(String s, DataOutput stream)

Here you can find the source of writeString(String s, DataOutput stream)

Description

write String

License

Apache License

Declaration

public static void writeString(String s, DataOutput stream) throws IOException 

Method Source Code

//package com.java2s;
/*//  w  w w  . j a v a 2  s . c o  m
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    private final static ThreadLocal<byte[]> myBuffer = new ThreadLocal<byte[]>() {
        protected byte[] initialValue() {
            return new byte[1024];
        }
    };

    public static void writeString(String s, DataOutput stream) throws IOException {
        if (s == null) {
            stream.writeInt(-1);
            return;
        }

        final int len = s.length();
        stream.writeInt(len);
        if (len == 0) {
            return;
        }

        int charsWritten = 0;
        final byte[] buff = myBuffer.get();
        while (charsWritten < len) {
            final int bytesWritten = Math.min((len - charsWritten) * 2, buff.length);
            for (int i = 0; i < bytesWritten; i += 2) {
                char aChar = s.charAt(charsWritten++);
                buff[i] = (byte) ((aChar >>> 8) & 0xFF);
                buff[i + 1] = (byte) ((aChar) & 0xFF);
            }
            stream.write(buff, 0, bytesWritten);
        }
    }
}

Related

  1. writeString(DataOutput output, String s)
  2. writeString(final String data, final DataOutput out, final int length)
  3. writeString(final String string, final DataOutput out)
  4. writeString(String par0Str, DataOutput par1DataOutput)
  5. writeString(String s, DataOutput output)
  6. writeString(String s, DataOutput stream)