JFileChooser を使用して textArea からデータを保存していますが、ユーザーが新しいファイルを既存の名前で保存できないようにしたいと考えています。コードを実行するたびに、保存しようとしているファイルの名前を変更するようにユーザーに 1 回だけ促します。ループを使用して、ユーザーが新しい名前を入力するまで既存のファイル名を使用できないようにするにはどうすればよいですか? これが私がこれまでに持っているものです:
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;
}
}
});
私はこれを2日間続けていますが、本当に助けが必要です!! よろしくお願いします!
これが編集されたコードです。@ 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;
}