【问题标题】:How to realize "mklink /H" (hardlinking) in Java?如何在 Java 中实现“mklink /H”(硬链接)?
【发布时间】:2011-12-20 10:06:40
【问题描述】:

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

  • 所以必须找到现有文件
  • 然后做一个硬链接
  • 然后删除旧文件

我开始实施,但我只知道如何创建文件。在谷歌上,我没有发现任何关于 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 ");
}

【问题讨论】:

    标签: java file-io hardlink mklink


    【解决方案1】:

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

    1. JAVA 1.7 支持硬链接。

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

    2. JNA,JNA 允许您进行本地系统调用。

      https://github.com/twall/jna

    3. JNI,你可以使用 C++ 创建一个硬链接,然后通过 JAVA 调用它。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      链接(软链接或硬链接)是不向标准 Java API 公开的操作系统功能。我建议您使用Runitme.exec()ProcessBuilder 从java 运行命令mklink /h

      或者尝试找到包装它的第 3 方 API。还要检查 Java 7 中的新功能。不幸的是,我不熟悉它,但我知道他们添加了丰富的文件系统 API。

      【讨论】:

      • thx 我写了一个获取字符串的方法,它可以工作 yuhuu :)
      • 看起来像这样: m.runScriptLocal("cmd /c mklink c:\\mklink\\test\\test.txt c:\\mklink\\test.txt");
      【解决方案3】:

      为了后代,我使用以下方法在 *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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-21
        • 2017-03-25
        • 1970-01-01
        • 2020-07-15
        • 2014-02-06
        • 1970-01-01
        • 1970-01-01
        • 2015-05-02
        • 2018-07-13
        相关资源
        最近更新 更多