3

ファイル「C:\ xxx.log」から「C:\ mklink\xxx.log」へのハードリンクを作成したい。cmdではもちろん機能しますが、このユースケース用のソフトウェアを作成したいと思います。

  • したがって、既存のファイルを見つける必要があります
  • 次に、ハードリンクを作成します
  • 次に、古いファイルを削除します

実装を始めましたが、ファイルの作成方法を知っています。グーグルで私はJavaのmklink\Hについて何も見つけませんでした。

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

3 に答える 3

4

JAVAでハードリンクを作成する方法は3つあります。

  1. JAVA1.7はハードリンクをサポートします。

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

  2. JNA、JNAを使用すると、ネイティブシステムコールを実行できます。

    https://github.com/twall/jna

  3. JNI、C ++を使用してハードリンクを作成し、JAVAを介して呼び出すことができます。

お役に立てれば。

于 2011-12-20T10:15:36.893 に答える
1

リンク(ソフトまたはハード)は、標準のJavaAPIに公開されていないOS機能です。またはmklink /hを使用してJavaからコマンドを実行することをお勧めします。Runitme.exec()ProcessBuilder

または、これをラップするサードパーティのAPIを探してみてください。また、Java 7の新機能も確認してください。残念ながら、私はJava 7に精通していませんが、リッチファイルシステムAPIが追加されていることは知っています。

于 2011-12-20T10:16:11.563 に答える
1

後世のために、私は次の方法を使用して* nix/OSXまたはWindowsでリンクを作成します。Windowsmklink /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);
    }
}
于 2014-02-15T17:10:52.763 に答える