Program to Create Hard Links in Java
Below is the code implementation to create hard link to the original file.
Java
// Java program to demonstrate the creation of hardlink import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class HardLinkExample { public static void main(String args[]) { try { // specify the original file and the hard link path Path originalPath = Paths.get( "original.txt" ); Path hardLinkPath = Paths.get( "hard_link.txt" ); // check if the original file exists if (!Files.exists(originalPath)) { // if the original file does not exist, create it Files.createFile(originalPath); System.out.println( "Original file created." ); } // create a hard link Files.createLink(hardLinkPath, originalPath); System.out.println( "Hard link created successfully." ); } catch (IOException e) { System.out.println( "Error creating hard link: " + e.getMessage()); } } } |
Output
Original file created. Hard link created successfully.
Explanation of the above program:
- In the above program, it first checks if the original file
original.txt
Files.createFile
. - It then creates a hard link named
hard_link.txt
that points to the original file usingFiles.createLink
. - If the hard link created successfully, it will print the output message.
How to Create Symbolic Links and Hard Links in Java?
Java file system provides both hard and symbolic links, which let us make references to files and directories. In this article, we will learn how to create symbolic links and hard links in Java.
- Soft Links or Symbolic Links: Symbolic links are names of files or directories. They may stretch across several file systems and serve as pointers to the original file or directory.
- Hard Links: Multiple directory entries pointing to the same disk are known as hard links. All files that reference the same will update in response to changes made to one file.