views:

363

answers:

2

Hi to all,

I have doubt in renaming java files... My application has to rename the incoming file which is mdb,dbf,xls,xml,etc. format. I used the following source code.

eg:

String filename = "D:/sample.mdb";
File filediriden = new File(filename);
String[] filetype = filename.split("\\.");
System.out.println("Filetype :"+filetype[1]);
String newfilename = "D:/new."+filetype[1];
File newfilediriden = new File(newfilename);
System.out.println("New File Name "+newfilename);
boolean rename = filediriden.renameTo(newfilediriden);
if(rename)
   System.out.println("File Renamed");
if(filediriden.isFile()){
    System.out.println("filename" + filediriden.getName());
}else{
    System.out.println("not a filename");
}


OUTPUT:
Filetype  : mdb
New File Name D:/new.mdb
File Renamed
not a filename

After that I checked whether its a file or not but its not going into that...Help plz...

+3  A: 
boolean rename = filediriden.renameTo(newfilediriden);
if(filediriden.isFile()){

After you rename the file, the old File object (filediriden) still points to the old name, which no longer exists. You want to check using the new File object (newfilediriden).

filetype[1]

Also, there could be files with more than one dot in them, so maybe filetype[filetype.length-1] is safer.

Thilo
+1  A: 

The problem is you're checking the filedirden instead of newfiledirden.
At the point of test, filedirden doesn't exist anymore, as the file it points to was renamed.

abyx