0

In the below code I am checking whether file ends with CSV extension. My question is : If file ends with xls extension I need to change to csv.

Example: AA.xls file to AA.CSV (only extension change).

public boolean accept(File dir, String name) {

                    System.out.println("CSV Files Present in Dir are:   " + name);

                    return name.toLowerCase().endsWith("csv");
                 }
            });
Cœur
  • 37,241
  • 25
  • 195
  • 267
123HIS
  • 103
  • 3
  • 5
  • 19

5 Answers5

1

The File.renameTo(File dest) function is your friend. So, you have a file, get it's path, replace xls with csv and create a new File object from that. Then rename your file and you're done.

blalasaadri
  • 5,990
  • 5
  • 38
  • 58
1

If you simply change an xls-file to csv by changing the file extension it might not be readable afterwards, unless the file really is CSV "encoded".

To simply rename the file use blalasaadri's answer and use File.renameTo(File dest), but if you have a real XLS file, you need a library like Apache POI to parse the file and then store the data in a CSV file.

LuigiEdlCarno
  • 2,410
  • 2
  • 21
  • 37
0

You have a method renameTo in the File class. You can use it to change the extension of the file.

Have a look at the javadocs.

JHS
  • 7,761
  • 2
  • 29
  • 53
0

you can try this way

String name="a.xls";
        String []z=name.split("\\.");
        if(z[1].equals("xls")){
            z[1]=".csv";
        }
        System.out.println(z[0]+z[1]);
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
  • 1
    This assumes there is only one `.` in the file name. – Alan Sep 17 '13 at 08:33
  • @Alan I assume Op can write a method which passes an arguement of String type – SpringLearner Sep 17 '13 at 08:35
  • 1
    I don't see how that relates. My concern was for situations where `name = "bar.foo.xls";`. With the above code, this xls file would be ignored, since the element following the first `.` is not xls. – Alan Sep 23 '13 at 18:07
0
// File (or directory) with old name
File file = new File("oldname");
// File (or directory) with new name
File file2 = new File("newname");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success)
{
// File was not successfully renamed
}
Iren Patel
  • 729
  • 1
  • 10
  • 22