Q:

Rename if file exists on upload jsp

I'm follow this tutorial 
http://www.tutorialspoint.com/jsp/jsp_file_uploading.htm
My Question is :
How to rename file name while uploading ?
How to rename a file if the name already exists ?

A:

In the backend JSP file just below the // Write the file section
if( fileName.lastIndexOf("\\") >= 0 ){
  file = new File( filePath + 
  fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
  file = new File( filePath + 
  fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}

// rename if file exists
int i = 1;
while (file.exists()) { // keep renaming as file_(2) , file_(3) etc.
    String path = file.getAbsolutePath();
    int iDot = path.lastIndexOf(".");
    file = new File(path.substring(0, iDot) +
           "_(" + ++i + ")" + path.substring(iDot));
}

fi.write( file ) ;

Please, note that I'm assuming the files would always end with some .ext extension.

