以下是试图将gzip格式的数据存储在表“ TESTBYTEA”中的Java代码.我正在使用postgresql数据库. TESTBYTEA表具有BYTEA类型的一列“数据”.我想压缩数据并存储它.从数据库读取时,我想解压缩并读取它.但是我收到一个异常消息“不是GZIP格式”.
public static void main(String[] args){
insertBytes(connection);
readBytes(connection);
connection.close();
}
public static void insertBytes(Connection connection) throws FileNotFoundException, IOException, sqlException{
File file = new File("C:test.txt");
FileReader fileReader = new FileReader(file);
char[] cbuf = new char[2000];
int read = fileReader.read(cbuf);
String str = new String (cbuf);
byte[] bytes = gzip(str);
Statement statement = connection.createStatement();
int result = statement.executeUpdate("INSERT INTO TESTBYTEA (data) VALUES ('\\\\x"+bytes+"')");
System.out.println(result);
}
public static void readBytes(Connection connection) throws sqlException, IOException{
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select data from testbytea");
while(rs.next()){
byte[] bs = rs.getBytes(1);
String str = gunzip(bs);
System.out.println(str);
}
}
private static String gunzip(byte[] bytes) throws IOException {
Reader reader = new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(bytes)), "US-ASCII");
StringBuffer sbuf = new StringBuffer();
char[] buffer = new char[32 * 1024];
int nread;
while ((nread = reader.read(buffer)) >= 0) {
sbuf.append(buffer, 0, nread);
}
String s = sbuf.toString();
reader.close();
return s;
}
private static byte[] gzip(String s) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
Writer writer = new OutputStreamWriter(gzos, "US-ASCII");
writer.write(s);
writer.flush();
gzos.finish();
byte[] bytes = baos.toByteArray();
writer.close();
return bytes;
}
但是我收到以下异常
Exception in thread "main" java.io.IOException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:141)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:56)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:65)
at postgresjdbc.PostgresJDBC.gunzip(PostgresJDBC.java:237)
at postgresjdbc.PostgresJDBC.readBytes(PostgresJDBC.java:230)
at postgresjdbc.PostgresJDBC.main(PostgresJDBC.java:208)
Java Result: 1
对此任何帮助表示赞赏.
解决方法:
您的问题是如何插入字节:
"INSERT INTO TESTBYTEA (data) VALUES ('\\\\x"+bytes+"')"
会产生类似
INSERT INTO TESTBYTEA (data) VALUES ('\\x[B@187c6c7')
(实际上,.toString()中的byte []引用用于字节数组.
您为什么不使用准备好的陈述?
PreparedStatement pstmt = connection.prepareStatement(
"INSERT INTO TESTBYTEA (data) VALUES (?)");
pstmt.setBytes(1, bytes);
pstmt.executeUpdate();
编辑:
不要忘记:
pstmt.close();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。