001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: HardLink.java 271 2012-02-02 20:15:24Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.io;
009    
010    import com.sun.jna.Library;
011    import com.sun.jna.Native;
012    
013    import java.io.File;
014    import java.io.IOException;
015    
016    /**
017     * Supports hard-linking of files on UNIX systems.
018     *
019     * <p>
020     * This class requires the <a href="https://github.com/twall/jna">JNA</a> library.
021     */
022    public final class HardLink {
023    
024        private static final LibC LIBC = (LibC)Native.loadLibrary("c", LibC.class);
025    
026        private HardLink() {
027        }
028    
029        /**
030         * Create a hard link from {@code src} to {@code dest}.
031         *
032         * @param src existing file to be linked to {@code dest}
033         * @param dest new file that will link to {@code src}
034         * @throws IOException if the operation fails
035         */
036        public static void link(File src, File dest) throws IOException {
037            if (LIBC.link(src.toString(), dest.toString()) != 0)
038                throw new IOException(LIBC.strerror(Native.getLastError()));
039        }
040    
041        /**
042         * Command line test method.
043         */
044        static void main(String[] args) throws Exception {
045            HardLink.link(new File(args[0]), new File(args[1]));
046        }
047    
048        private interface LibC extends Library {
049            int link(String from, String to);
050            String strerror(int errno);
051        }
052    }
053