2016-05-01 115 views
-1

你好,有人可以告訴我正確的代碼,以便確認消息時,該文件被覆蓋問?覆蓋JFileChooser java

{ 
    int index = cCont.getSelectedIndex(); 
    log.info("index=" + index); 
    if (m_att.getEntryCount() < index) 
     return; 
    String fileName = getFileName(index); 
    String ext = fileName.substring (fileName.lastIndexOf(".")); 
    log.config("Ext=" + ext); 

    JFileChooser chooser = new JFileChooser(); 
    chooser.setDialogType(JFileChooser.SAVE_DIALOG); 
    chooser.setDialogTitle(Msg.getMsg(Env.getCtx(), "AttachmentSave")); 
    File f = new File(fileName); 
    chooser.setSelectedFile(f); 
    // Show dialog 
    int returnVal = chooser.showSaveDialog(this); 
    if (returnVal != JFileChooser.APPROVE_OPTION) 
     return; 
    File saveFile = chooser.getSelectedFile(); 
    if (saveFile == null) 
     return; 
    log.config("Save to " + saveFile.getAbsolutePath()); 
    m_attachment.getEntryFile(index, saveFile); 
} 

回答

0
JFileChooser chooser = new JFileChooser(); 
chooser.setFileFilter(new FileNameExtensionFilter("Text File", "txt")); 
chooser.setMultiSelectionEnabled(false); 

int returnValue = chooser.showSaveDialog(mainFrame); 
if (returnValue != JFileChooser.APPROVE_OPTION) { 
    return; 
} 

File saveFile = chooser.getSelectedFile(); 

if (saveFile.exists()) { 

    int returnVal = JOptionPane.showConfirmDialog(mainFrame, 
      "Overwrite existing file " + saveFile + "?", "Overwrite warning", JOptionPane.OK_CANCEL_OPTION, 
      JOptionPane.WARNING_MESSAGE); 
    if (returnVal == JOptionPane.CANCEL_OPTION) { 
     return; 
    } 

    try { 
     saveFile.delete(); 
    } catch (Exception ex) { 

    } 
} 
1

所有一個JFileChooser所做的就是返回選擇的File。所以一旦你得到選定的文件,你需要檢查它是否存在,然後提示用戶進行確認。

所以基本的代碼如下:

if (saveFile.exists()) 
{ 
    int response = JOptionPane.showConfirmDialog(...); 
} 

退房從How to Use Option Panes了Swing教程以獲取更多信息和工作實例的部分。