Here you can find the source of toDirectBuffer(String s)
public static ByteBuffer toDirectBuffer(String s)
//package com.java2s; // are made available under the terms of the Eclipse Public License v1.0 import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class Main { public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[0]); public static ByteBuffer toDirectBuffer(String s) { return toDirectBuffer(s, StandardCharsets.ISO_8859_1); }/*from ww w . ja va 2 s . co m*/ public static ByteBuffer toDirectBuffer(String s, Charset charset) { if (s == null) return EMPTY_BUFFER; byte[] bytes = s.getBytes(charset); ByteBuffer buf = ByteBuffer.allocateDirect(bytes.length); buf.put(bytes); buf.flip(); return buf; } /** Allocate ByteBuffer in flush mode. * The position and limit will both be zero, indicating that the buffer is * empty and in flush mode. * @param capacity capacity of the allocated ByteBuffer * @return Buffer */ public static ByteBuffer allocateDirect(int capacity) { ByteBuffer buf = ByteBuffer.allocateDirect(capacity); buf.limit(0); return buf; } /** * Put data from one buffer into another, avoiding over/under flows * @param from Buffer to take bytes from in flush mode * @param to Buffer to put bytes to in fill mode. * @return number of bytes moved */ public static int put(ByteBuffer from, ByteBuffer to) { int put; int remaining = from.remaining(); if (remaining > 0) { if (remaining <= to.remaining()) { to.put(from); put = remaining; from.position(from.limit()); } else if (from.hasArray()) { put = to.remaining(); to.put(from.array(), from.arrayOffset() + from.position(), put); from.position(from.position() + put); } else { put = to.remaining(); ByteBuffer slice = from.slice(); slice.limit(put); to.put(slice); from.position(from.position() + put); } } else put = 0; return put; } }