gpt4 book ai didi

java - 使用 SQLITEOpenHelper 在 Android SQLite 中存储 BLOB

转载 作者:太空狗 更新时间:2023-10-29 12:58:22 25 4
gpt4 key购买 nike

有没有办法使用 SQLOpenHelper 将 BLOB 存储到 Android 的 SQLite 中?

我的 BLOB 类型为 InputStream

最佳答案

SQLite 不支持流式传输 BLOB 或 CLOB 数据。您有四种选择:

  • 将 InputStream 转换为 byte[]。这只有在您有足够的内存时才有效(见下文)。
  • 使用 FileOutputStream 或支持流式传输的 Android API
  • 将数据拆分成小块,然后存储在 SQLite 中
  • 使用适用于 Android 且支持流式传输的数据库。我只知道 H2 database .但请注意,Android 对 H2 的支持是非常新的。在这种情况下,您需要使用 JDBC API,并且您可能想要启用 LOBs in the database , 否则每个大的 BLOB 都存储在一个单独的文件中。

要将 InputStream 转换为字节数组,您可以使用:

public static byte[] readBytesAndClose(InputStream in) throws IOException {
try {
int block = 4 * 1024;
ByteArrayOutputStream out = new ByteArrayOutputStream(block);
byte[] buff = new byte[block];
while (true) {
int len = in.read(buff, 0, block);
if (len < 0) {
break;
}
out.write(buff, 0, len);
}
return out.toByteArray();
} finally {
in.close();
}
}

关于java - 使用 SQLITEOpenHelper 在 Android SQLite 中存储 BLOB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3640267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com