如何从Blob转换为bytearray和字符串

时间:2019-07-05 11:48:26

标签: android arrays sqlite blob

我正在学习制作字典应用程序。我有一个小的数据库,在一个表中有20个单词,在另一个表中有20个单词的定义。但是定义是BLOB类型的。而且我无法获得其正常的字符串类型。这是我尝试的代码:

public byte[] word_value(int a) throws UnsupportedEncodingException {
        c = database.rawQuery("select body from items A inner join items_info B on A.id = B.id where B.id = '" + a + "';" , null);
        while (c.moveToNext()){
            byte[] blob = c.getBlob(0);
            String s = new String(blob, StandardCharsets.UTF_8);
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        }
        return null;
    }

它获取值,但不转换为字符串

enter image description here

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

自夸方法会帮助您

/**
 * @param data
 * @return
 */
public static String byteToHex(byte[] data) {
    StringBuilder buf = new StringBuilder();
    for (byte b : data) {
        int halfbyte = (b >>> 4) & 0x0F;
        int two_halfs = 0;
        do {
            buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
            halfbyte = b & 0x0F;
        } while (two_halfs++ < 1);
    }
    return buf.toString();
}

/**
 * @param str
 * @return
 */
public static byte[] hexToBytes(String str) {
    if (str == null) {
        return null;
    } else if (str.length() < 2) {
        return null;
    } else {
        int len = str.length() / 2;
        byte[] buffer = new byte[len];
        for (int i = 0; i < len; i++) {
            buffer[i] = (byte) Integer.parseInt(
                    str.substring(i * 2, i * 2 + 2), 16);

        }
        return buffer;
    }
}

/**
 * @param data
 * @return
 */
public static String byteToString(byte[] data) {
    String string = null;
    try {
        string = new String(data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Logger.w(TAG, e);
    }
    return string;
}

/**
 * @param data
 * @return
 */
public static byte[] stringToByte(String data) {
    byte[] bytes = null;
    try {
        bytes = data.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        Logger.w(TAG, e);
    }
    return bytes;
}

/**
 * @param input
 * @return
 */
public static byte[] hexStringToByteArray(String input) {
    int len = input.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)
                + Character.digit(input.charAt(i + 1), 16));
    }
    return data;
}