Java File Write via ByteBuffer writeString(ByteArrayOutputStream bout, String val)

Here you can find the source of writeString(ByteArrayOutputStream bout, String val)

Description

write String

License

Open Source License

Declaration

public static void writeString(ByteArrayOutputStream bout, String val) throws IOException 

Method Source Code

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class Main {
    private final static String ENCODING = "UTF-8";

    public static void writeString(ByteArrayOutputStream bout, String val) throws IOException {
        if (val == null) {
            writeInt(bout, -1);//w w  w .j av  a 2s .c  o  m
            return;
        }
        if (val.length() == 0) {
            writeInt(bout, 0);
            return;
        }
        byte[] bytes = val.getBytes(ENCODING);
        writeInt(bout, bytes.length);
        bout.write(bytes);
    }

    public static void writeInt(ByteArrayOutputStream bout, int val) throws IOException {
        ByteBuffer b = ByteBuffer.allocate(4);
        b.putInt(val);
        byte[] bytes = b.array();
        bout.write(bytes);
    }
}

Related

  1. writeLong(OutputStream in, long i)
  2. writeLong(OutputStream os, Long d)
  3. writeLong(RandomAccessFile raFile, long num)
  4. writeObject(Serializable serializable)
  5. writeShort(int i, DataOutput out)
  6. writeStringContents(String contents, WritableByteChannel channel)
  7. writeStringData(DataOutputStream mDataOutputStream, String token)
  8. writeStringToSocketChannel(String text, SocketChannel sc)
  9. writeToFile(String path, ByteOrder byteOrder)