Java Byte Array from getBytesFromString(final String str, final int length, final String coding)

Here you can find the source of getBytesFromString(final String str, final int length, final String coding)

Description

Converts a string to an array of bytes with the length specified

License

Open Source License

Parameter

Parameter Description
str the string to convert
length the size of the byte array

Return

the array of bytes converted from the string

Declaration

public static byte[] getBytesFromString(final String str, final int length, final String coding) 

Method Source Code

//package com.java2s;
/*//from www  .ja  va  2s.c o  m
 * @(#) Helpers.java
 *
 * Created on 22.04.2006 by Daniel Becker (quippy@quippy.de)
 *
 *-----------------------------------------------------------------------
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *----------------------------------------------------------------------
 */

import java.io.UnsupportedEncodingException;

public class Main {
    /**
     * Converts a string to an array of bytes with the length specified
     * @since 23.12.2008
     * @param str the string to convert
     * @param length the size of the byte array
     * @return the array of bytes converted from the string
     */
    public static byte[] getBytesFromString(final String str, final int length, final String coding) {
        byte[] result = new byte[length];
        int len = str.length();
        if (len > length)
            len = length;
        try {
            System.arraycopy(str.getBytes(coding), 0, result, 0, len);
        } catch (UnsupportedEncodingException ex) {
            System.arraycopy(str.getBytes(), 0, result, 0, len);
        }
        return result;
    }
}

Related

  1. getBytesFromList(List values)
  2. getBytesFromObject(Serializable data)
  3. getBytesFromObject(Serializable obj)
  4. getBytesFromResource(String resource)
  5. getBytesFromStream(int length, ByteArrayInputStream bais)
  6. getBytesFromText(String text, String charset)
  7. getBytesInCodePage(final String string, final int codepage)
  8. getBytesInUsAscii(String s)
  9. getBytesISO88591(String s)

  10. HOME | Copyright © www.java2s.com 2016