0

If I save a file like test.csv and open it, JFileChooser will see it like test.cvs. When I am going to save it again it adds csv so i'm getting test.csv.csv and so on. I know it has something to do with FileWriter because I added extension to a file like:

File fajl = new File (fc.getSelectedFile()+".csv");

Is there any way to remove extension when file is opened, and again when it is saved, i wont get test.csv.csv?

I tryed with endsWith and no luck.

This solved it for me. I used Tom van der Woerdt solution with slight modification:

 String s = fc.getSelectedFile().toString();
               int p = s.lastIndexOf('.');
               if(p>0){ s=s.substring(0,p);System.out.print(s);}

                 fajl = new File (s+".csv");

System.out.print is there just to test output name of the file.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Anak1n
  • 149
  • 1
  • 2
  • 12

1 Answers1

0

You can check if the file name has a trailing '.csv' and add it only when necessary:

String filePath = fc.getSelectedFile();

// add file extension if not already provided
if (!filePath.matches(".*\.csv$"))
{
  filePath += ".csv"
}

File fajl = new File(filePath);
usr1234567
  • 21,601
  • 16
  • 108
  • 128