![]() |
Java Programming provides a lot of packages for handling real-time problems but in our case, we need to create a File with a unique name. For this, there are different solutions in Java. Like Using timestamp series as the file name or creating a unique random number and then assigning that number as a file name. In this article, we will learn two different solutions for creating a file with a unique name. Approaches to create a file with a unique nameBelow are the different approaches for creating a file with a unique name in Java.
Now we will discuss each approach with one Java example for a better understanding of the concept. Programs to create a file with a unique name in Java1. TimestampsIn this approach, we have taken the Current Data Time by using the LocalDateTime class in Java which is available in java.util package and we have used this Date Time format for getting unique names for files that are yyyyMMddHHmmss. Java
Output
File created successfully: path/to/your/directory/file_20240201065644.txt Explanation of the above Program:
2. Random NumberIn this example, we have generated a random number then this number set as file name. You can observe below code for getting the point. Java
Output
File created successfully: path/to/your/directory/file_3936.txt 3. Using UUIDIn this approach, we have used UUID, This UUID provides one method that is UUID.randomUUID() which is used for generating unique values, after that this value is assigned as file name. Java
Output
File created successfully: path/to/your/directory/file_d558bf18-3615-449d-a9cd-a6228a392694.txt 4. Atomic CounterThis is the one of the ways for create a file with a unique name in Java. This approach is used for while you want create file names in sequence manner. Java
Output
File created successfully: path/to/your/directory/file_1.txt Explanation of the above Program:
|
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |