Java Program to Create a File with a Unique Name
Last Updated :
24 Apr, 2025
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
// Java program to create a unique
// File with a timestamp in the filename
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;
// Class definition for UniqueFileNameExampleOne
public class UniqueFileNameExampleOne
{
// Main method
public static void main(String[] args)
{
try {
// Specify the directory where you want to create the file
String directoryPath = "path/to/your/directory";
// Generate a unique file name using timestamp
String uniqueFileName = generateUniqueFileName();
// Combine the directory path and unique file name to get the full file path
Path fullPath = Paths.get(directoryPath, uniqueFileName);
// If the directory does not exist, create the directory
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
// Create the file
Files.createFile(fullPath);
System.out.println("File created successfully: " + fullPath);
}
// Handle file creation errors
catch (IOException e)
{
e.printStackTrace();
}
}
// Helper method to generate a unique file name using a timestamp
private static String generateUniqueFileName()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = dateFormat.format(new Date());
return "file_" + timestamp + ".txt";
}
}
OutputFile 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
// Java program to create a unique
// File with a random number in the filename
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
// Class definition for UniqueFileNameExampleTwo
public class UniqueFileNameExampleTwo
{
// Main method
public static void main(String[] args)
{
try
{
// Specify the directory where you want to create the file
String directoryPath = "path/to/your/directory";
// Generate a unique file name using a random number
String uniqueFileName = generateUniqueFileName();
// Combine the directory path and unique file name to get the full file path
Path fullPath = Paths.get(directoryPath, uniqueFileName);
// If the directory does not exist, create the directory
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
// Create the file
Files.createFile(fullPath);
System.out.println("File created successfully: " + fullPath);
}
// Handle file creation errors
catch (IOException e)
{
e.printStackTrace();
}
}
// Helper method to generate a unique file name using a random number
private static String generateUniqueFileName()
{
// Create a Random object
Random random = new Random();
// Generate a random number
int randomNumber = random.nextInt(100000);
// Return the formatted unique file name
return "file_" + randomNumber + ".txt";
}
}
OutputFile 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
// Java program to create a unique
// File with a UUID in the filename
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
// Class definition for UniqueFileNameExampleThree
public class UniqueFileNameExampleThree
{
// Main method
public static void main(String[] args)
{
try
{
// Specify the directory where you want to create the file
String directoryPath = "path/to/your/directory";
// Generate a unique file name using UUID
String uniqueFileName = generateUniqueFileName();
// Combine the directory path and unique file name to get the full file path
Path fullPath = Paths.get(directoryPath, uniqueFileName);
// If the directory does not exist, create the directory
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
// Create the file
Files.createFile(fullPath);
System.out.println("File created successfully: " + fullPath);
}
// Handle file creation errors
catch (IOException e)
{
e.printStackTrace();
}
}
// Helper method to generate a unique file name using UUID
private static String generateUniqueFileName()
{
// Create a UUID object
UUID uuid = UUID.randomUUID();
// Return the formatted unique file name
return "file_" + uuid.toString() + ".txt";
}
}
OutputFile 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
// Java program to create a unique file
// With an atomic counter in the filename
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;
// Class definition for UniqueFileNameExample
public class UniqueFileNameExample
{
// Atomic counter for generating unique file names
private static final AtomicLong counter = new AtomicLong();
// Main method
public static void main(String[] args)
{
try
{
// Specify the directory where you want to create the file
String directoryPath = "path/to/your/directory";
// Generate a unique file name using an atomic counter
String uniqueFileName = generateUniqueFileName();
// Combine the directory path and unique file name to get the full file path
Path fullPath = Paths.get(directoryPath, uniqueFileName);
// If the directory does not exist, create the directory
if (!Files.exists(fullPath.getParent())) {
Files.createDirectories(fullPath.getParent());
}
// Create the file
Files.createFile(fullPath);
System.out.println("File created successfully: " + fullPath);
}
// Handle file creation errors
catch (IOException e)
{
e.printStackTrace();
}
}
// Helper method to generate a unique file name using an atomic counter
private static String generateUniqueFileName()
{
// Return the formatted unique file name with an incremented atomic counter
return "file_" + counter.incrementAndGet() + ".txt";
}
}
OutputFile 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.
Similar Reads
Java Program to Create a New File
There are two standard methods to create a new file, either directly with the help of the File class or indirectly with the help of the FileOutputStream class by creating an object of the file in both approaches. Methods to Create Files in JavaThere are two methods mentioned below Using the File Cla
4 min read
Java Program to Create a Temporary File
A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement. Type of Fil
5 min read
Java Program to Get the Creation Time of a File
Use java.nio package for extracting the creation date and time of any file through java. To extract the date and time of the file use BasicFileAttributes class. java.nio package helps us to get the creation time, last access time, and last modified time, it works for both file and directory. Approac
2 min read
Java Program to Create a File in a Specified Directory
Creating a file in a specific directory using Java can be done in various ways. This is done using predefined packages and Classes. In this article, we will learn about how to create a file in a specified directory. Methods to Create a File in a Specified DirectoryThree such methods to create a file
3 min read
Java Program to Create String from Contents of a File
A File is a computer resource which is deployed to store different types of data such as text, image, video, to name a few. It is basically a collection of data bound to a single entity. While using your computer, it becomes essential to be able to deal with files and in this article we will be lear
6 min read
Java Program to Convert File to a Byte Array
Here, we will go through the different ways to convert file to byte array in Java. Note: Keep a check that prior doing anything first. Create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs. Methods: Using rea
3 min read
Java Program to Get the Last Access Time of a File
Every file which stores a lot of data, also has its own set of data ( known as metadata) which can be used to get the properties of that file. Such data types are called attributes. Java provides a basis for accessing any attributes of any file such as creation time of the file, last access time, la
2 min read
Java Program to Write into a File
FileWriter class in Java is used to write character-oriented data to a file as this class is character-oriented because it is used in file handling in Java. There are many ways to write into a file in Java as there are many classes and methods which can fulfill the goal as follows: Using writeString
6 min read
Java Program to Write a Paragraph in a Word Document
Java provides us various packages in-built into the environment, which facilitate the ease of reading, writing, and modifying the documents. The package org.apache.poi.xwpf.usermodel provides us the various features of formatting and appending the content in word documents. There are various classes
3 min read
Java Program to Print all Unique Words of a String
Java program to print all unique words present in the string. The task is to print all words occurring only once in the string. Illustration: Input : Welcome to Geeks for Geeks. Output : Welcome to for Input : Java is great.Python is also great. Output : Java Python also Methods: This can be done in
4 min read