java zip文件插入数据库下载
时间: 2023-11-29 09:53:03 浏览: 72
java 文件上传下载到数据库.pdf
以下是Java中将ZIP文件插入到数据库并下载的示例代码:
```java
import java.io.*;
import java.sql.*;
public class ZipToDatabase {
public static void main(String[] args) {
String zipFilePath = "example.zip";
String dbUrl = "jdbc:mysql://localhost:3306/mydb";
String dbUser = "root";
String dbPassword = "password";
String tableName = "zip_files";
try {
// Read ZIP file into byte array
byte[] zipFileBytes = readZipFile(zipFilePath);
// Insert ZIP file into database
insertZipFileIntoDatabase(zipFileBytes, dbUrl, dbUser, dbPassword, tableName);
// Download ZIP file from database
downloadZipFileFromDatabase(tableName, dbUrl, dbUser, dbPassword);
} catch (Exception e) {
e.printStackTrace();
}
}
// Read ZIP file into byte array
public static byte[] readZipFile(String zipFilePath) throws IOException {
File file = new File(zipFilePath);
byte[] buffer = new byte[(int) file.length()];
try (FileInputStream fis = new FileInputStream(file)) {
fis.read(buffer);
}
return buffer;
}
// Insert ZIP file into database
public static void insertZipFileIntoDatabase(byte[] zipFileBytes, String dbUrl, String dbUser, String dbPassword, String tableName) throws SQLException {
try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword)) {
String sql = "INSERT INTO " + tableName + "(file_data) VALUES(?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setBytes(1, zipFileBytes);
pstmt.executeUpdate();
}
}
}
// Download ZIP file from database
public static void downloadZipFileFromDatabase(String tableName, String dbUrl, String dbUser, String dbPassword) throws SQLException, IOException {
try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword)) {
String sql = "SELECT file_data FROM " + tableName;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
InputStream is = rs.getBinaryStream("file_data");
FileOutputStream fos = new FileOutputStream("downloaded.zip");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
}
}
}
}
}
}
```
在此示例中,我们首先将ZIP文件读入字节数组中,然后将其插入到数据库中。我们使用预处理语句来执行SQL查询,并将字节数组传递给`setBytes()`方法。在下载ZIP文件时,我们使用`getBinaryStream()`方法获取`ResultSet`中的二进制流,并将其写入到本地文件中。
阅读全文