JAVA에서 Unique한 키값 얻어 오기
자바에서 Unique한 키값을 얻어오기 위해서는 UUID라는 기능을 사용하면 된다.
100% Unique한 값을 보장할수는 없지만 거의 유일한 키값을 준다고 한다.
package com.gsshop.im4java; import java.io.File; import java.util.UUID; public class UniqueFileName { public static void main(String[] args) { System.out.println(doMakeUniqueFileName("c:\\sample\\","girl.jpg")); } public static String doMakeUniqueFileName(String serverPath, String fileName) { String extension = fileName.substring(fileName.lastIndexOf(".")); String uniqueFileName = null; boolean flag = true; while (flag) { uniqueFileName = getUniqueFileName(); flag = doCheckFileExists(serverPath+uniqueFileName+extension); } return serverPath+uniqueFileName+extension; } private static boolean doCheckFileExists(String fullPath) { return new File(fullPath).exists(); } private static String getUniqueFileName() { return UUID.randomUUID().toString(); } }
UUID API 원문
http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html
-
public final class UUID
- extends Object
-
- implements Serializable, Comparable<UUID>
-
A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value.
There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below).
The layout of a variant 2 (Leach-Salz) UUID is as follows: The most significant long consists of the following unsigned fields:
0xFFFFFFFF00000000 time_low 0x00000000FFFF0000 time_mid 0x000000000000F000 version 0x0000000000000FFF time_hi
The least significant long consists of the following unsigned fields:
0xC000000000000000 variant 0x3FFF000000000000 clock_seq 0x0000FFFFFFFFFFFF node
The variant field contains a value which identifies the layout of the
UUID
. The bit layout described above is valid only for a
UUID
with a variant value of 2, which indicates the Leach-Salz variant.
The version field holds a value that describes the type of this
UUID
. There are four different basic types of UUIDs: time-based, DCE security, name-based, and randomly generated UUIDs. These types have a version value of 1, 2, 3 and 4, respectively.
For more information including algorithms used to create
UUID
s, see RFC 4122: A Universally Unique IDentifier (UUID) URN Namespace, section 4.2 "Algorithms for Creating a Time-Based UUID".
- Since:
- 1.5
- See Also:
- Serialized Form