
/*
 * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
 *
 * $Id$
 */

package org.dellroad.stuff.io;

import com.sun.jna.Library;
import com.sun.jna.Native;

import java.io.File;
import java.io.IOException;

/**
 * Supports hard-linking of files on UNIX systems.
 *
 * <p>
 * This class requires the <a href="https://github.com/twall/jna">JNA</a> library.
 */
public final class HardLink {

    private static final LibC LIBC = (LibC)Native.loadLibrary("c", LibC.class);

    private HardLink() {
    }

    /**
     * Create a hard link from {@code src} to {@code dest}.
     *
     * @param src existing file to be linked to {@code dest}
     * @param dest new file that will link to {@code src}
     * @throws IOException if the operation fails
     */
    public static void link(File src, File dest) throws IOException {
        if (LIBC.link(src.toString(), dest.toString()) != 0)
            throw new IOException(LIBC.strerror(Native.getLastError()));
    }

    /**
     * Command line test method.
     */
    static void main(String[] args) throws Exception {
        HardLink.link(new File(args[0]), new File(args[1]));
    }

    private interface LibC extends Library {
        int link(String from, String to);
        String strerror(int errno);
    }
}


@@ -252,40 +252,120 @@
 iles
- on UNIX systems.%0A *%0A * %3Cp%3E%0A * T
+.%0A *%0A * %3Cp%3E%0A * On Java &gt;= 1.7, this class uses %7B@link java.nio.file.Files#createLink%7D.%0A * On Java &lt; 1.7, t
 his 
@@ -437,17 +437,59 @@
  library
-.
+%0A * and only works on UNIX systems.%0A * %3C/p%3E
 %0A */%0Apub
@@ -539,67 +539,17 @@
 tic 
-final LibC LIBC = (LibC)Native.loadLibrary(%22c%22, LibC.class)
+LibC libc
 ;%0A%0A 
@@ -901,24 +901,25 @@
 ption %7B%0A
+%0A
         
 if (LIBC
@@ -914,16 +914,304 @@
     
-if (LIBC
+// Try JDK 1.7 Files.createLink() first%0A        try %7B%0A            Class.forName(%22java.nio.files.Files%22).getMethod(%22createLink%22).invoke(null, dest, src);%0A            return;%0A        %7D catch (Exception e) %7B%0A            // ignore%0A        %7D%0A%0A        // Fall-back to JNA%0A        if (HardLink.getLibC()
 .lin
@@ -1289,12 +1289,26 @@
 ion(
-LIBC
+HardLink.getLibC()
 .str
@@ -1337,32 +1337,211 @@
 ror()));%0A    %7D%0A%0A
+    private static LibC getLibC() %7B%0A        if (HardLink.libc == null)%0A            HardLink.libc = (LibC)Native.loadLibrary(%22c%22, LibC.class);%0A        return HardLink.libc;%0A    %7D%0A%0A
     /**%0A     * C

Use Files.createLink() on JDK >= 1.7.