简体   繁体   中英

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. 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 .

I assume that the images are store as BLOB. You should get the binaryStream from the resultset, read it and write into a file in the selected path. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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