Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listFiles() of File not working on symbolic links?

I have the following File object pointing to a directory via symbolic link,

File directory = new File("/path/symlink/foo/bar");
String[] files = directory.listFiles();

listFiles() returns null, is this because of the symlink? if yes, how will I go about this if I really want to list the files in bar using the path that contains a symlink?

like image 675
setzamora Avatar asked Mar 18 '10 16:03

setzamora


People also ask

How do you force a symbolic link?

Ln Command to Create Symbolic Links By default, the ln command creates a hard link. Use the -s option to create a soft (symbolic) link. The -f option will force the command to overwrite a file that already exists.

Can you symlink files?

You can create a symlink (symbolic) by using the ln command in the command line. Symbolic links are useful because they act as shortcuts to a file or directory. In this article, I will go over how to use the ln command to create a symlink to a file or directory.

Can symbolic links point to files that don't exist?

You can create a symlink to practically anything, including things that don't exist.

Do Symlinks work both ways?

From this a symlink is merely another name for a named path to either a file or a folder. In other words they only point one way.


2 Answers

According to what I've seen while Googling this puzzling behavior, Java requires that you call .getCanonicalFile() on a File whose path contains a link before you can use it in other file operations.

So:

File directory = new File("/path/symlink/foo/bar").getCanonicalFile();
String[] files = directory.listFiles();
like image 189
Powerlord Avatar answered Oct 05 '22 23:10

Powerlord


You could read the Symbolic LINK

like image 23
mickthompson Avatar answered Oct 05 '22 23:10

mickthompson