KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > oreilly > servlet > multipart > DefaultFileRenamePolicy


1 // Copyright (C) 2002 by Jason Hunter <jhunter_AT_acm_DOT_org>.
2
// All rights reserved. Use of this class is limited.
3
// Please see the LICENSE for more information.
4

5 package com.oreilly.servlet.multipart;
6
7 import java.io.*;
8
9 /**
10  * Implements a renaming policy that adds increasing integers to the body of
11  * any file that collides. For example, if foo.gif is being uploaded and a
12  * file by the same name already exists, this logic will rename the upload
13  * foo1.gif. A second upload by the same name would be foo2.gif.
14  * Note that for safety the rename() method creates a zero-length file with
15  * the chosen name to act as a marker that the name is taken even before the
16  * upload starts writing the bytes.
17  *
18  * @author Jason Hunter
19  * @version 1.1, 2002/11/05, making thread safe with createNewFile()
20  * @version 1.0, 2002/04/30, initial revision, thanks to Yoonjung Lee
21  * for this idea
22  */

23 public class DefaultFileRenamePolicy implements FileRenamePolicy {
24   
25   // This method does not need to be synchronized because createNewFile()
26
// is atomic and used here to mark when a file name is chosen
27
public File rename(File f) {
28     if (createNewFile(f)) {
29       return f;
30     }
31     String JavaDoc name = f.getName();
32     String JavaDoc body = null;
33     String JavaDoc ext = null;
34
35     int dot = name.lastIndexOf(".");
36     if (dot != -1) {
37       body = name.substring(0, dot);
38       ext = name.substring(dot); // includes "."
39
}
40     else {
41       body = name;
42       ext = "";
43     }
44
45     // Increase the count until an empty spot is found.
46
// Max out at 9999 to avoid an infinite loop caused by a persistent
47
// IOException, like when the destination dir becomes non-writable.
48
// We don't pass the exception up because our job is just to rename,
49
// and the caller will hit any IOException in normal processing.
50
int count = 0;
51     while (!createNewFile(f) && count < 9999) {
52       count++;
53       String JavaDoc newName = body + count + ext;
54       f = new File(f.getParent(), newName);
55     }
56
57     return f;
58   }
59
60   private boolean createNewFile(File f) {
61     try {
62       return f.createNewFile();
63     }
64     catch (IOException ignored) {
65       return false;
66     }
67   }
68 }
69
Popular Tags