简体   繁体   English

使用JFileChooser从数据库保存文件

[英]saving a file from a database using JFileChooser

I wanted to ask, how to download a file from a database and save it Using Jfilechooser. 我想问一下,如何从数据库下载文件并使用Jfilechooser保存它。 Can you give me some idea how this would work ? 你能给我一些想法吗?

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");
}

I don't know what should I do after JFileChooser.APPROVE_OPTION . JFileChooser.APPROVE_OPTION之后,我不知道该怎么办。

I assume that the images are store as BLOB. 我假设图像存储为BLOB。 You should get the binaryStream from the resultset, read it and write into a file in the selected path. 您应该从结果集中获取binaryStream,对其进行读取,然后将其写入所选路径中的文件中。 For example: 例如:

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: The connections and streams are defined with try with resources for auto close. PD:使用try定义连接和流,并使用资源进行自动关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM