Java 从数据库下载文件通常涉及到以下几个基础概念:
以下是一个简单的示例,展示如何从数据库中下载一个二进制文件(如图像):
import java.io.*;
import java.sql.*;
public class FileDownloader {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
String query = "SELECT file_data FROM files WHERE file_id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setInt(1, 1); // 假设我们要下载的文件ID为1
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("file_data");
InputStream inputStream = blob.getBinaryStream();
FileOutputStream outputStream = new FileOutputStream("downloaded_file.jpg");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件下载成功!");
} else {
System.out.println("未找到文件!");
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
希望这些信息对你有所帮助!如果有更多问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云