The server in question was an Apache server. As Nathan said in his comment, directory indexing had to be enabled.
Enable Indexing
See: http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/
Approach 1:
- Open Apache config file: (
etc/httpd/httpd.conf
or etc/apache2/apache2.conf
)
Add the following:
<Directory /var/www/example.com/directory>
Options Indexes FollowSymLinks
</Directory>
Save and close
- Restart Apache
Approach 2:
- Create/Open a file called
.htaccess
in directory you want indexed.
- Append the following line:
Options Indexes
Use this in Java
Now that indexing is enabled you can actually access the list of subdirectories/files from your java code.
URL url = new URl("http://www.example.com/directory"); //or just "http://www.example.com/" for the root dir, if there isn't an index.html
Scanner sc = new Scann(url.openStream());
while(sc.hasNextLine())
System.out.println(sc.nextLine());
The output of this snippet will be
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of directory</title>
</head>
<body>
<h1>Index of directory/</h1>
<ul><li><a href="subdir/">subdir</a></li>
<li><a href="file.txt">file.txt</a></li>
</ul>
</body></html>
Parse that URL however you choose. You will also get a directory listing as a webpage if you visit http://www.example.com/directory/