Question

i want to create a hardlink from a file "C:\xxx.log" to "C:\mklink\xxx.log" . In cmd it works of course, but i want to write a software for this usecase.

  • So have to locate the existing file
  • Then make a hardlink
  • Then delete the old file

I started to implement but, i just know how to create a file. On google i found nothing about mklink \H for Java.

public void createFile() {
     boolean flag = false;

     // create File object
     File stockFile = new File("c://mklink/test.txt");

     try {
         flag = stockFile.createNewFile();
     } catch (IOException ioe) {
          System.out.println("Error while Creating File in Java" + ioe);
     }

     System.out.println("stock file" + stockFile.getPath() + " created ");
}
Was it helpful?

Solution

There are 3 ways to create a hard link in JAVA.

  1. JAVA 1.7 Supports hardlinks.

    http://docs.oracle.com/javase/tutorial/essential/io/links.html#hardLink

  2. JNA, The JNA allows you to make native system calls.

    https://github.com/twall/jna

  3. JNI, you could use C++ to create a hardlink and then call it through JAVA.

Hope this helps.

OTHER TIPS

Link (soft or hard) is a OS feature that is not exposed to standard java API. I'd suggest you to run command mklink /h from java using Runitme.exec() or ProcessBuilder.

Or alternatively try to find 3rd party API that wraps this. Also check what's new in Java 7. Unfortunately I am not familiar with it but I know that they added rich file system API.

For posterity, I use the following method to create links on *nix/OSX or Windows. On windows mklink /j creates a "junction" which seems to be similar to a symlink.

protected void makeLink(File existingFile, File linkFile) throws IOException {
    Process process;
    String unixLnPath = "/bin/ln";
    if (new File(unixLnPath).canExecute()) {
        process =
                Runtime.getRuntime().exec(
                        new String[] { unixLnPath, "-s", existingFile.getPath(), linkFile.getPath() });
    } else {
        process =
                Runtime.getRuntime().exec(
                        new String[] { "cmd", "/c", "mklink", "/j", linkFile.getPath(), existingFile.getPath() });
    }
    int errorCode;
    try {
        errorCode = process.waitFor();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException("Link operation was interrupted", e);
    }
    if (errorCode != 0) {
        logAndThrow("Could not create symlink from " + linkFile + " to " + existingFile, null);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top