Java Program to Create a File with a Unique Name
Last Updated :
01 Feb, 2024
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 name
Below are the different approaches for creating a file with a unique name in Java.
- Using Timestamps
- Using Random Number
- Using UUID (Universally Unique Identifier)
- Using Atomic Counter
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 Java
1. Timestamps
In 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
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UniqueFileNameExampleOne
{
public static void main(String[] args)
{
try {
String directoryPath = "path/to/your/directory" ;
String uniqueFileName = generateUniqueFileName();
Path fullPath = Paths.get(directoryPath, uniqueFileName);
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
Files.createFile(fullPath);
System.out.println( "File created successfully: " + fullPath);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static String generateUniqueFileName()
{
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMMddHHmmss" );
String timestamp = dateFormat.format( new Date());
return "file_" + timestamp + ".txt" ;
}
}
|
Output
File created successfully: path/to/your/directory/file_20240201065644.txt
Explanation of the above Program:
- In the above example, we have added a check to create the directory if it doesn’t exist using
Files.createDirectories()
.
- We have used type
Path
instead of String
for better handling.
2. Random Number
In 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
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
public class UniqueFileNameExampleTwo
{
public static void main(String[] args)
{
try
{
String directoryPath = "path/to/your/directory" ;
String uniqueFileName = generateUniqueFileName();
Path fullPath = Paths.get(directoryPath, uniqueFileName);
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
Files.createFile(fullPath);
System.out.println( "File created successfully: " + fullPath);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static String generateUniqueFileName()
{
Random random = new Random();
int randomNumber = random.nextInt( 100000 );
return "file_" + randomNumber + ".txt" ;
}
}
|
Output
File created successfully: path/to/your/directory/file_3936.txt
3. Using UUID
In 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
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
public class UniqueFileNameExampleThree
{
public static void main(String[] args)
{
try
{
String directoryPath = "path/to/your/directory" ;
String uniqueFileName = generateUniqueFileName();
Path fullPath = Paths.get(directoryPath, uniqueFileName);
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
Files.createFile(fullPath);
System.out.println( "File created successfully: " + fullPath);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static String generateUniqueFileName()
{
UUID uuid = UUID.randomUUID();
return "file_" + uuid.toString() + ".txt" ;
}
}
|
Output
File created successfully: path/to/your/directory/file_d558bf18-3615-449d-a9cd-a6228a392694.txt
4. Atomic Counter
This 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
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicLong;
public class UniqueFileNameExample
{
private static final AtomicLong counter = new AtomicLong();
public static void main(String[] args)
{
try
{
String directoryPath = "path/to/your/directory" ;
String uniqueFileName = generateUniqueFileName();
Path fullPath = Paths.get(directoryPath, uniqueFileName);
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
Files.createFile(fullPath);
System.out.println( "File created successfully: " + fullPath);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static String generateUniqueFileName()
{
return "file_" + counter.incrementAndGet() + ".txt" ;
}
}
|
Output
File created successfully: path/to/your/directory/file_1.txt
Explanation of the above Program:
- In the above example, the code generates unique file names using an atomic counter and creates files in a specified directory path.
- This states uniqueness by incrementing a counter atomically for each new file created and handles file creation errors with basic exception handling.
Share your thoughts in the comments
Please Login to comment...