O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.5. Renaming Files

Problem

You want to rename the uploaded files according to a standard policy or to avoid conflicts with existing files that have the same name.

Solution

Create a class that implements the com.oreilly.servlet.multipart.FileRenamePolicy interface, or use the DefaultFileRenamePolicy class. Then use that class as a parameter in the constructor for the com.oreilly.servlet.MultipartRequest class.

Discussion

The com.oreilly.servlet.multipart package contains a FileRenamePolicy interface that can be used when you want to implement a particular file-renaming policy with file uploads.

The DefaultFileRenamePolicy class renames an uploaded file whose name conflicts with an existing file by adding a number to the uploaded filename. For example, if index.txt already exists, then the DefaultFileRenamePolicy class renames the uploaded file index1.txt; and if a second file is uploaded with the same name it will be renamed index2.txt, and so on.

If you want to implement your own renaming policy, then create your own class that implements the FileRenamePolicy interface, then implement the class's rename(java.io.File file) method to initiate the renaming action.

This code sample shows a MultipartRequest constructor from Example 8-3. This time, the constructor adds a DefaultFileRenamePolicy object as a constructor parameter:

MultipartRequest mpr = new MultipartRequest(
  request,webTempPath,(5 * 1024 * 1024),new DefaultFileRenamePolicy( ));

Make sure to include the following import statements ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required