Java String to Byte Array getBytes(String s)

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

Description

get Bytes

License

Open Source License

Declaration

public final static byte[] getBytes(String s) 

Method Source Code


//package com.java2s;
/*//from www  .  j  av a2s. com
 * @(#)ASCIIUtility.java   1.7 00/05/22
 *
 * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Sun Microsystems, Inc.
 * Use is subject to license terms.
 *
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    public final static byte[] getBytes(String s) {
        char[] chars = s.toCharArray();
        int size = chars.length;
        byte[] bytes = new byte[size];

        for (int i = 0; i < size;)
            bytes[i] = (byte) chars[i++];
        return bytes;
    }

    public final static byte[] getBytes(InputStream is) throws IOException {

        int len;
        int size = 1024;
        byte[] buf;

        if (is instanceof ByteArrayInputStream) {
            size = is.available();
            buf = new byte[size];
            len = is.read(buf, 0, size);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            buf = new byte[size];
            while ((len = is.read(buf, 0, size)) != -1)
                bos.write(buf, 0, len);
            buf = bos.toByteArray();
        }
        return buf;
    }
}

Related

  1. convertStringToByteArray(String string)
  2. convertStringToBytes(String string)
  3. getBytes(String k)
  4. getBytes(String k)
  5. getBytes(String outputFile, Map queries)
  6. getBytes(String s)
  7. getBytes(String s)
  8. getBytes(String s)
  9. getBytes(String s)