twid
twid

Reputation: 6686

Copying symbolic link for different OS's in java

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..

Upvotes: 1

Views: 1711

Answers (4)

Jasty
Jasty

Reputation: 81

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

Upvotes: 1

twid
twid

Reputation: 6686

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

Upvotes: 2

Puce
Puce

Reputation: 38132

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

Upvotes: 2

CAMOBAP
CAMOBAP

Reputation: 5657

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

Upvotes: 0

Related Questions