[英]Saving certain text from JTextArea to a file using JFileChooser
[英]saving a file from a database using JFileChooser
我想问一下,如何从数据库下载文件并使用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
之后,我不知道该怎么办。
我假设图像存储为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:使用try定义连接和流,并使用资源进行自动关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.