Tuesday, August 21, 2012

Problem with File.renameTo in java file io


renameTo method in java.io.file may not work always [For eg: During File Upload - if destination and source is in different file system, renameTo fails]
As per the documentation of java.io.file -

renameTo

public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname. Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.



Alternative approach is you can use org.apache.commons.io.FileUtils .

copyFile



public static void copyFile(File srcFile,
                            File destFile)
                     throws IOException
Copies a file to a new location preserving the file date.This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it.

Overriding struts validate method for showing custom error message

Overriding struts validate method for showing custom error message during FileUpload
 @SuppressWarnings("unchecked")  
      public void validate()  
      {  
       List<String> uploadErrors = (List<String>)getActionErrors();  
       if (getFieldErrors().get("upload") != null)  
       {  
        uploadErrors.addAll((List<String>)getFieldErrors().get("upload"));  
       }  
       for (String err : uploadErrors)  
       {  
        if ( err.startsWith("Enter the Error Message to be overridden"))  
        {  
         clearErrorsAndMessages();  
         addActionError("Enter new error message");  
         break;  
        }  
       }  
      }  

Tuesday, August 07, 2012