Tutorial :Java reports alias (symlink) as size 0 on Mac OSX. How do I get the true file size?



Question:

File file = new File("path to file alias foo");  

where "path to file alias foo" is an alias reports file size to be 0 instead of the actual file size. I found a workaround to test for aliases:

public boolean isLink() {          try {              if (file.getAbsolutePath().equals(file.getCanonicalPath())) {                  return false;              }          } catch (IOException ex) {              logger.severe(ex.getMessage());          }          return true;      }  

EDIT Actually this code does not work, as pointed out by a poster below. I was trying to adapt a solution from a linux symlink example, but I didn't realize that finder aliases and symlinks were not the same.

NOT! this seems to work, but ....

file.getCanonicalFile().length();  

still reports file length to be 0. Can anyone point me in the right direction?


Solution:1

Finder aliases are a different beast altogether from normal symbolic links. The *nix tools on OS X are not aware of aliases at all, because they're stored in the resource fork, I believe. If you install osxutils, you can use this shell command to get the target of an alias:

hfsdata -e the-alias  

From Java, I don't know of a better way of doing this other than calling Runtime.exec(...).

Also, I just a did a quick check, and your function for detecting aliases does not work. AFAICT, Java is not aware of Finder aliases. If you really want to support them, then you'll either need to use something like osxutils, or use some platform-specific code to read resource forks (will probably involve JNI). Neither option is pretty.

If you go the JNI route, check out the Alias Manager Reference documentation. The relevant functions are FSIsAliasFile and FSResolveAliasFile.


Solution:2

You can use the FileRef Interface from the O'Reilly Java NIO API. I believe the getAttribute() method can handle symbolic links as you want, but I have not tried it on Mac OSX. From the docs:

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed and so the method returns the file attribute of the symbolic link.


Solution:3

size = new File(file.getCanonicalPath()).length();


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »