2016-05-01 12 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のチュートリアルからのセクションをチェックしてください。

関連する問題