Reads the attributes of the target file and creates a link, assigning the attributes from the target to the link. - Java File Path IO

Java examples for File Path IO:Symbolic Link

Description

Reads the attributes of the target file and creates a link, assigning the attributes from the target to the link.

Demo Code

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    Path link = FileSystems.getDefault().getPath("test");
    Path target = FileSystems.getDefault().getPath("C:/folder1/photos",
        "test.jpg");

    try {/*w w  w  .ja  va 2s .  c om*/
      PosixFileAttributes attrs = Files.readAttributes(target,
          PosixFileAttributes.class);
      FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions
          .asFileAttribute(attrs.permissions());

      Files.createSymbolicLink(link, target, attr);
    } catch (IOException | UnsupportedOperationException | SecurityException e) {
      if (e instanceof SecurityException) {
        System.err.println("Permission denied!");
      }
      if (e instanceof UnsupportedOperationException) {
        System.err.println("An unsupported operation was detected!");
      }
      if (e instanceof IOException) {
        System.err.println("An I/O error occured!");
      }
      System.err.println(e);
    }

  }
}

Result


Related Tutorials