首页 > 解决方案 > 如何从 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;
    }

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

在此处输入图像描述

任何帮助表示赞赏

标签: androidarrayssqliteblob

解决方案


自爆方法会帮助你

/**
 * @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;
}

推荐阅读