Generate filename for uploaded file in JAVA

    /**
     * Takes the original file name's suffix and generated a new random file name with the oringial file suffix.
     * @param oldFileName The original file name of the uploaed file.
     * @return String The generated new random file name.
     */
    private String convertFileName(String originalFileName) {

    	// Get the extension (suffix) of the original file name.
    	originalFileName = originalFileName.trim();

        //... Find the position of the last dot.  Get extension.
        int dotPos = originalFileName.lastIndexOf(".");
        String extension = originalFileName.substring(dotPos);

    	Random random = new Random((new Date()).getTime());
    	String fileName =  "uploadfile_" + generateRandomStringForFileName(8) + Math.abs(random.nextInt()) + extension;
    	return fileName;
    }

    /**
     * Generates a random string.
     * @param length The length of the random string.
     * @return The generated random string.
     */
    private static String generateRandomStringForFileName (int length) {
    	String randomString = "";
    	for (int i=0; i<length; i++) {
    		randomString += generateRandomCharForFileName();
    	}
    	return randomString;
    }

    /**
     * Generates a random character for the file name.
     * @return char Returns a random character.
     */
    private static char generateRandomCharForFileName() {
    	int zuf = generateRandomIntForFileName(25);
   		zuf += 97;
   		return ((char)zuf);
    }

    /**
     * Generates a random int.
     * @param max The maximum number for the character.
     * @return int
     */
    public static int generateRandomIntForFileName(int max){
    	int number;
    	Random generate = new Random();
    	number = generate.nextInt(max);
    	return number;
    }

Subscribe to comments Comment | Trackback |
Post Tags:

Browse Timeline


Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>