1

Is it possible to copy a symbolic link in java... Basically I want is to copy only symbolic link no containing files, where symbolic link points to..

twid
  • 6,368
  • 4
  • 32
  • 50
  • What you mean by 'copy symbolic link'. Are you want to know target file/folder of symlink? – CAMOBAP Sep 28 '12 at 12:40
  • i can dived this in to two parts... While copying files First Identify Symbolic link and then copy it without Copying containing files... – twid Sep 28 '12 at 12:53

4 Answers4

2

I haven't tried, but Ihink you can use LinkOption.NOFOLLOW_LINKS when using Files.copy (Java SE 7)

http://docs.oracle.com/javase/7/docs/api/java/nio/file/LinkOption.html

Puce
  • 37,247
  • 13
  • 80
  • 152
2

I got the way.. First i need to identify Is it a symbolic link by

Path file = ...;
boolean isSymbolicLink =
    Files.isSymbolicLink(file);

Then i can create same symbolic link at destination by

    Path newLink = ...;
Path existingFile = ...;
try {
    Files.createLink(newLink, existingFile);
} catch (IOException x) {
    System.err.println(x);
} catch (UnsupportedOperationException x) {
    // Some file systems do not
    // support adding an existing
    // file to a directory.
    System.err.println(x);
}
twid
  • 6,368
  • 4
  • 32
  • 50
1

Sure you can do that. Check out method copy(Path source, Path target, CopyOption... options) from class Files. Specifying LinkOption.NOFOLLOW_LINKS as copy option will make the copy method do what you want.

This behavior is universal when it comes to working with links as demostrated here:

Path target = Paths.get("c://a.txt");
Path symbolicLink = Paths.get("c://links//symbolicLink.txt");

// creates test link
Files.createSymbolicLink(symbolicLink, target);

BasicFileAttributes targetAttributes = Files.readAttributes(symbolicLink, BasicFileAttributes.class);
BasicFileAttributes linkAttributes = Files.readAttributes(symbolicLink, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);

System.out.println("File attribute - isSymbolicLink\tTarget: " + targetAttributes.isSymbolicLink() + "\t\t\t\tLink: " + linkAttributes.isSymbolicLink());
System.out.println("File attribute - size\t\tTarget: " + targetAttributes.size() + "\t\t\t\tLink: " + linkAttributes.size());
System.out.println("File attribute - creationTime:\tTarget: " + targetAttributes.creationTime() + "\tLink: " + linkAttributes.creationTime());

This code outpus:

File attribute - isSymbolicLink: Target: false                        Link: true
File attribute - size:           Target: 8556                         Link: 0
File attribute - creationTime:   Target: 2013-12-08T16:43:19.55401Z   Link: 2013-12-14T16:09:17.547538Z

You can visit my post for more information on links in NIO.2

Jasty
  • 81
  • 1
  • 3
0

All possible operations with symlinks that available in JRE from the box described in this page

CAMOBAP
  • 5,523
  • 8
  • 58
  • 93