Java ByteBuffer from String asByteBuffer(String s)

Here you can find the source of asByteBuffer(String s)

Description

as Byte Buffer

License

Open Source License

Declaration

public static ByteBuffer asByteBuffer(String s) 

Method Source Code

//package com.java2s;
/**//from w w w  .j a  v  a  2s.  c om
 * Copyright 2007-2016, Kaazing Corporation. All rights reserved.
 *
 * 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.nio.ByteBuffer;

import java.nio.charset.Charset;

public class Main {
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    public static final Charset US_ASCII = Charset.forName("US-ASCII");

    public static ByteBuffer asByteBuffer(String s) {
        if (null == s) {
            return null;
        }
        if (s.length() < 1024) { // we will only check isASCII if message less then 1K.
            return isASCII(s) ? US_ASCII.encode(s) : UTF_8.encode(s);
        } else {
            return UTF_8.encode(s);
        }
    }

    public static ByteBuffer asByteBuffer(byte[] bytes) {
        return (bytes != null) ? ByteBuffer.wrap(bytes) : null;
    }

    public static boolean isASCII(String s) {
        int size = s.length();
        char c;
        for (int i = 0; i < size; i++) {
            c = s.charAt(i);
            if (!(c >= 0 && c <= 127)) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. asByteBuffer(String data)
  2. stringToByteBuffer(String data)
  3. stringToByteBuffer(String string)
  4. stringToNullTerminatedByteBuffer(String s)
  5. toByteBuffer(final String s)