簡體   English   中英

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM