簡體   English   中英

JFileChooser:防止用戶以現有名稱保存文件

[英]JFileChooser: Preventing User from saving a file under existing name

我正在使用JFileChooser來保存來自textArea的數據,並且我想防止用戶以現有名稱保存其新文件。 每次執行代碼時,它只會提示用戶一次更改他們嘗試保存的文件的名稱。 在用戶輸入新名稱之前,我可以使用哪種方式使循環阻止用戶使用現有文件名? 這是我到目前為止的內容:

JButton OKSavebutton = new JButton("OK");
    OKSavebutton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            final JFileChooser fc = new JFileChooser();
            final int result = JOptionPane.showConfirmDialog(fc, "Save new Observation Well File?", "Save File", 
                    JOptionPane.OK_CANCEL_OPTION);
            fc.setCurrentDirectory(new File("C:/Users/281925/Desktop/mads/User Saved Internal Contamination Problem/Observation Wells"));

            FileNameExtensionFilter madsType = new FileNameExtensionFilter("MADS file (*.mads)", "mads");
            fc.setFileFilter(madsType);
            fc.addChoosableFileFilter(madsType);
            fc.setAcceptAllFileFilterUsed(false);

        int returnVal = fc.showSaveDialog(fc);
        File f = new File(fc.getSelectedFile()+".mads");

            switch(result){
            case JOptionPane.OK_OPTION:
                if (f.exists()){
                    int result1 = JOptionPane.showConfirmDialog(fc, "The file name exists. Please input new File name", "New File Name", 
                            JOptionPane.OK_CANCEL_OPTION);
                    fc.showSaveDialog(fc);
                }
                try{    
                    String fileExt = ".mads";
                        //create a buffered writer to write to a file
                        BufferedWriter out = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath() + fileExt));
                        out.write(textArea.getText());//write contents of the TextArea to the file
                        out.close();//close the file stream
                    }
                    catch(Exception e){  //catch any exceptions and write to the console
                        System.out.println(e.getMessage());
                    }

                return;
            case JOptionPane.CANCEL_OPTION:
                fc.cancelSelection();
                return;
                default:
                    return;
                    }

        }

    });

我已經做了兩天了,我真的需要幫助!! 謝謝,麻煩您了!

這是編輯后的代碼。 感謝@ luk2302的協助。 我確實需要稍微調整一下,但是現在它就像一個咒語一樣工作:)

int result1 = fc.showSaveDialog(fc);
        File f = new File(fc.getSelectedFile()+".mads");

        /* loop until the user entered a file that does not exist yet */
        while(f.exists()) { 

          result = JOptionPane.showConfirmDialog(fc, "The file name exists. Please input new File name", "New File Name", JOptionPane.OK_CANCEL_OPTION);

          if(result == JOptionPane.OK_OPTION){
             fc.showSaveDialog(fc);
         }
          /*Create new file and set it equal to f*/
          File f1 = new File(fc.getSelectedFile() + ".mads"); 
          f = f1;
        }

            /* return if user cancels */
        if(result == JOptionPane.CANCEL_OPTION) { 
            fc.cancelSelection();
            return;
          }
        /* if the user finally selected a non existing file do whatever needs to be done. */
        if (result == JOptionPane.OK_OPTION) {
          try { 
            String fileExt = ".mads";
            //create a buffered writer to write to a file
            BufferedWriter out = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath() + fileExt));
            out.write(textArea.getText());//write contents of the TextArea to the file
            out.close();//close the file stream
            } catch(Exception e){  //catch any exceptions and write to the console
            System.out.println(e.getMessage());
            }
          return;
          }

只需執行以下操作:

/* loop until the user entered a file that does not exist yet */
while(fc.getSelectedFile().exists()) { 
  result = JOptionPane.showConfirmDialog(fc, "The file name exists. Please input new File name", "New File Name", JOptionPane.OK_CANCEL_OPTION);
  fc.showSaveDialog(fc);
  /* return if user cancels */
  if(result == JOptionPane.CANCEL_OPTION) { 
    fc.cancelSelection();
    return;
  }
}

/* if the user finally selected a non existing file do whatever needs to be done. */
if (result == JOptionPane.OK_OPTION) {
  try { 
    String fileExt = ".mads";
    //create a buffered writer to write to a file
    BufferedWriter out = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath() + fileExt));
    out.write(textArea.getText());//write contents of the TextArea to the file
    out.close();//close the file stream
  } catch(Exception e){  //catch any exceptions and write to the console
    System.out.println(e.getMessage());
  }
  return;
}

還要注意,您分配了int returnVal = fc.showSaveDialog(fc); 從未使用過,而是在其余代碼中使用result的值。 因此,將變量重命名為` int result = fc.showSaveDialog(fc);”。

只需重寫JFileChooser的approveSelection方法

JFileChooser fileChooser = new JFileChooser()
        {
            @Override
            public void approveSelection()
            {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG)
                {
                    int result = JOptionPane.showConfirmDialog(this,
                                                               String.format("%s already exists.%n Overwrite?", f.getName()),
                                                               "File already exists", JOptionPane.YES_NO_OPTION);

                    switch (result)
                    {
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.NO_OPTION:
                            return;
                        case JOptionPane.CLOSED_OPTION:
                            return;
                        case JOptionPane.CANCEL_OPTION:
                            cancelSelection();
                            return;
                    }
                }
                super.approveSelection();
            }
        };

重寫approveSelection()方法以防止/確認此情況:

import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class FileChooserSave
{
    public static void main(String[] args)
    {
        final JFileChooser chooser = new JFileChooser( new File(".") )
        {
            public void approveSelection()
            {
                if (getSelectedFile().exists())
                {
                    System.out.println("Do You Want to Overwrite File?");
                }
                else
                    super.approveSelection();
            }
        };

        chooser.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println(e);
            }
        });

        chooser.setSelectedFile( new File("something.rob") );
        int returnVal = chooser.showSaveDialog(null);


        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
           System.out.println(chooser.getSelectedFile() );
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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