以下是 java 代码,它试图以 gzip 格式将数据存储在表“TESTBYTEA”中。我正在使用 postgresql 数据库。 TESTBYTEA 表有一列 BYTEA 类型的“数据”。我想压缩数据并存储它。从数据库中读取时,我想解压缩并读取它。但我得到一个异常(exception)“不是 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')
(本质上,byte[]
引用用于字节数组的 .toString()
。
为什么不使用准备好的语句?
PreparedStatement pstmt = connection.prepareStatement(
"INSERT INTO TESTBYTEA (data) VALUES (?)");
pstmt.setBytes(1, bytes);
pstmt.executeUpdate();
编辑:
不要忘记:
pstmt.close();
关于java - 我们可以在postgresql中以gzip格式存储数据吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9296032/