I have a method that get text from a JTextArea, create a file and write text on it as code below:
public void createTxt() {
TxtFilter txt = new TxtFilter();
JFileChooser fSave = new JFileChooser();
fSave.setFileFilter(txt);
int result = fSave.showSaveDialog(this);
if(result == JFileChooser.APPROVE_OPTION) {
File sFile = fSave.getSelectedFile();
FileFilter selectedFilter = fSave.getFileFilter();
String file_name = sFile.getName();
String file_path = sFile.getParent();
try{
if(!sFile.exists()) {
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "Warning file • " + file_name + " • created succesfully in \n" + file_path);
} else {
String message = "File • " + file_name + " • already exist in \n" + file_path + ":\n" + "Do you want to overwrite?";
String title = "Warning";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION){
sFile.delete();
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "File • " + file_name + " • overwritten succesfully in \n" + file_path);
}
}
}
catch(IOException e) {
System.out.println("Error");
}
}
}
and a txt file filter
public class TxtFilter extends FileFilter{
@Override
public boolean accept(File f){
return f.getName().toLowerCase().endsWith(".txt")||f.isDirectory();
}
@Override
public String getDescription(){
return "Text files (*.txt)";
}
}
The file filter for txt works fine but what I want is to add “.txt” extension when I type file name.
How to I have to modify my code?
UPDATE
You pointed me out that the check for existing files doesn’t work. I’m sorry, I didn’t think of it when I suggested you to replace the
BufferedWriterline.Now, replace this:
with:
With this replacement, it isn’t now needed to replace the line of
BufferedWriter, adding.txtfor the extension. Then, replace that line with the line in the code you posted (withBufferedWriter out = new BufferedWriter(new FileWriter(sFile));instead ofBufferedWriter out = new BufferedWriter(new FileWriter(sFile+".txt"));).Now the program should work as expected.
I forgot to mention that you have to comment the line:
In this way, you’re creating an empty file, with the class
File.Just after this line, there is:
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));.With this line, you are creating again the same file. The writing procedure is happening two times! I think it’s useless to insert two instructions that are doing the same task.
Also, on the
BufferedWriterconstructor, you can append a string for the file name (it isn’t possible onFileconstructor), that’s the reason why I added+".txt"(the extension) tosFile.