以下是试图将数据以gzip格式存储在表格中的java代码" TESTBYTEA"。我正在使用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
对此有任何帮助表示赞赏。
答案 0 :(得分:3)
您的问题是如何插入字节:
"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();