How to get Java 7 to create "symbolic links to a directory" on Windows instead of "file symbolic links"?

I am using Oracle Java 7 on a 64-bit version of Windows.

When I create a symbolic link using Files.createSymbolicLink , I notice this behavior:

  • If the target is a directory, a "directory symbolic link" is created.
  • If the target is a file, a "symbolic link to the file" is created.
  • If the target does not exist, a "symbolic link to the file" is created.

The type of symbolic link is fixed and never changes , regardless of any changes in its purpose.

Using the built-in mklink for Windows, you can set the link type to be a "symbolic link directory". Is it possible to achieve this using my own Java API or some library?

One trivial and ugly way:

  • If the target is a directory, just create a link
  • If the target does not exist, create a new empty target directory, create a link and delete the directory.
  • If the target is a file ... process it (move it, apply # 2, move it back).

Fugly.

+6
source share
1 answer

Unfortunately, I do not see the possibility in the Java API for this.

I checked the Windows JRE code, and it looks like the solution is based on the file attributes themselves:

 try { WindowsFileAttributes windowsfileattributes = WindowsFileAttributes.get(windowspath2, false); if(windowsfileattributes.isDirectory() || windowsfileattributes.isDirectoryLink()) i |= 1; } 

The attributes themselves come from native code, and there seems to be no way to influence them.

Obviously, you have other options, such as manually accessing mklink or even controlling returned objects using something like PowerMock (which is clearly not intended for this purpose).

Another dirty option is to create proxies for all relevant classes: Path , FileSystem and FileSystemProvider .
The way it works is that Path returns a FileSystem , which FileSystemProvider returns - what you need to do is change the behavior of the FileSystemProvider.createSymbolicLink methods.

The createSymbolicLink method receives a varargs argument that is not currently used, you can pass an argument to it that tells your shell to override the way symbolic links are created - and here you are :)

After writing all this - the only question I have is - why do you need this behavior?

+2
source

Source: https://habr.com/ru/post/925823/


All Articles