在sqlite3数据库中读取gzipped字符串(Python写,Java Android读)
我正在尝试通过压缩来减小一个包含很多HTML的sqlite3数据库。我是用Python创建这个sqlite3数据库的,现在想在Android上正确解压。
我使用gzip来压缩HTML,并将其存储为BLOB格式在数据库中。这是我用Python写的创建sqlite3数据库的代码:
from sys import stdin, argv
import sqlite3
import gzip
import cStringIO
def compressBuf(buf):
zbuf = cStringIO.StringIO()
zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9)
zfile.write(buf)
zfile.close()
return zbuf.getvalue()
conn = sqlite3.connect(argv[1])
conn.text_factory = str
c = conn.cursor()
c.execute('''CREATE TABLE articles (
id INTEGER NOT NULL PRIMARY KEY,
name TEXT, category TEXT, html BLOB );''')
c.execute(' CREATE INDEX name_index on articles (name); ')
for line in stdin:
line = line.strip().split('\t')
line[-1] = sqlite3.Binary(compressBuf(line[-1]))
c.execute('INSERT INTO articles VALUES (?, ?, ?, ?);', line)
conn.commit()
c.close()
conn.close()
这是我在Android上的代码片段:
Cursor cursor = db.rawQuery("SELECT html FROM articles WHERE id = " + id + " limit 1;", null);
cursor.moveToFirst();
byte[] zhtml = cursor.getBlob(0);
ByteArrayInputStream is = new ByteArrayInputStream(zhtml);
GZIPInputStream gis = new GZIPInputStream(is, zhtml.length);
我遇到了一个异常,提示头部信息不正确:
java.io.IOException: unknown format (magic number 213c)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:84)
at tw.cse.o0o.MyApp.WebServer$ArticleHandler$1.writeTo(WebServer.java:196)
at org.apache.http.entity.EntityTemplate.writeTo(EntityTemplate.java:76)
at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:97)
at org.apache.http.impl.AbstractHttpServerConnection.sendResponseEntity(AbstractHttpServerConnection.java:182)
at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:209)
at tw.cse.o0o.MyApp.WebServer.run(SQLHelper.java:90)
通过Python解释器,我可以确认compressBuf函数返回了正确的gzip魔法数字0x1f8b:
>>> compressBuf('test')
'\x1f\x8b\x08\x00 \xba:O\x02\xff+I-.\x01\x00\x0c~\x7f\xd8\x04\x00\x00\x00'
[编辑]
好的,这是我发现的:
在Nexus One上,getBlob()函数会自动解压二进制数据,无论是zlib还是gzip。而在三星Galaxy Tab(第一代)上情况就不一样了。我还在寻找在我的Galaxy Tab上解压的方法……
1 个回答
0
'\x21\x3c
这个东西可以变成 '!<'
或者可能是 '<!'
,这取决于数据的字节顺序。我建议你去看看,可能在传输过程中,这些(以二进制形式的)gzipped数据被解压了。