gpt4 book ai didi

android - 在数据库 SQLite(适用于 Android)中添加一个 txt 文件,怎么样?

转载 作者:行者123 更新时间:2023-11-30 04:06:10 24 4
gpt4 key购买 nike

我应该把一个保存在手机sd卡中的txt文件放到Android的SQLite数据库中,但我不知道该怎么做,帮助我,我写了几行代码来做到这一点?

最佳答案

File转换为byte[],然后将其作为BLOB数据添加到sqlite中。也许您应该将它们转换为 Base64 格式以优化空间,您应该没问题。

如您所见,实现此类内容需要多个步骤,因此我只是添加了总体概述。如果您遇到困难,请询问更多详细信息。

编辑:我将提供关键点的代码。

要将文件转换为 byte[],请使用此代码段:

InputStream is = new FileInputStream(file); // where file is the .txt you want to convert
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();

将 byte[] 转换为 base64 字符串:

String dataToSave = Base64.encodeToString(bytes, Base64.DEFAULT);

byte[] dataToSave = Base64.encode(bytes, Base64.DEFAULT);

尽管您必须至少拥有 2.2 版才能支持 base 64 编码。

如果您选择了第一个实现,那么您的 sqlite 表中的任何 TEXT 字段就足够了,否则在您的表中创建一个列作为 BLOB。在创建要插入的 ContentValues 时,添加 values.put(KEY, dataToSave);

获取数据:

做相反的操作:1)从sqlite中获取数据,2)转换为byte[],3)转换为文件。

byte[] 转换为 File:

FileOutputStream out = new FileOutputStream(path); //file path as string
out.write(data); //data is the byte[]
out.flush();
out.close();

关于android - 在数据库 SQLite(适用于 Android)中添加一个 txt 文件,怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11621148/

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