如何实现;mklink/H";(硬链接)在Java中?

如何实现;mklink/H";(硬链接)在Java中?,java,file-io,hardlink,mklink,Java,File Io,Hardlink,Mklink,我想创建一个从文件“C:\xxx.log”到“C:\mklink\xxx.log”的硬链接。 在cmd中,它当然可以工作,但我想为这个用例编写一个软件 因此,我们必须找到现有的文件 然后进行硬链接 然后删除旧文件 我开始实现,但我只知道如何创建文件。在google上,我没有找到关于mklink\H for Java的任何信息 public void createFile() { boolean flag = false; // create File object

我想创建一个从文件“C:\xxx.log”到“C:\mklink\xxx.log”的硬链接。 在cmd中,它当然可以工作,但我想为这个用例编写一个软件

  • 因此,我们必须找到现有的文件
  • 然后进行硬链接
  • 然后删除旧文件
我开始实现,但我只知道如何创建文件。在google上,我没有找到关于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 ");
}

有3种方法可以在JAVA中创建硬链接

  • Java1.7支持硬链接

  • JNA,JNA允许您进行本机系统调用

  • <> > JNI,可以使用C++创建一个硬链接,然后通过java调用它。 希望这能有所帮助。

    链接(软或硬)是一种操作系统功能,不暴露于标准java API。我建议您使用
    Runitme.exec()
    ProcessBuilder
    从java运行命令
    mklink/h


    或者,也可以尝试寻找包装此内容的第三方API。还要检查Java7中的新功能。不幸的是,我不熟悉它,但我知道他们添加了丰富的文件系统API

    对于后代,我使用以下方法在*nix/OSX或Windows上创建链接。在windows
    mklink/j
    上创建一个类似于符号链接的“连接点”

    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);
        }
    }
    

    thx我写了一个方法,它得到一个字符串,它可以工作yuhuu:)如下所示:m.runScriptLocal(“cmd/c mklink c:\\mklink\\test\\test.txt c:\\mklink\\test.txt”);