我想问一下,如何从数据库下载文件并使用Jfilechooser保存它。你能告诉我这是怎么回事吗?
koneksi_db();
JFileChooser fs = new JFileChooser();
fs.setDialogTitle("save a file");
int result = fs.showSaveDialog(null);
try {
PreparedStatement ps = conn.prepareStatement("select * from file where nama = ?");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
fs.setCurrentDirectory(new File("/home/me/Documents"));
int tampak = fs.showSaveDialog(null);
if (tampak == JFileChooser.APPROVE_OPTION) {
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "sql error");
}
我不知道在JFileChooser.APPROVE_OPTION
之后我该怎么做。
答案 0 :(得分:0)
我假设图像存储为BLOB。您应该从结果集中获取binaryStream,读取它并写入所选路径中的文件。例如:
try (Connection connection = ConnectionHelper.getConnection();
PreparedStatenent ps =
conn.prepareStatement("select image from file where nama = ?")) {
ps.setXXX() // set the value for 'nama'
ResultSet rs = ps.executeQuery();
if(rs.next()){
fs.setCurrentDirectory(new File("/home/me/Documents"));
int tampak = fs.showSaveDialog(null);
if (tampak == JFileChooser.APPROVE_OPTION){
File file = fs.getSelectedFile();
try (InputStream stream = rs.getBinaryStream("image");
OutputStream output = new FileOutputStream(file)) {
byte[] buffer = new byte[4096];
while (stream.read(buffer) > 0) {
output.write(buffer);
}
}
}
}
rs.close();
} catch(FileNotFoundException fnfe){
// FileNotFoundException handling
} catch(IOException ioe) {
// IOException handling
} catch(SQLException sqle) {
// SQLException handling
}
}
PD:通过尝试使用资源进行自动关闭来定义连接和流。