所以我可以使用 HTTP 访问文件
URL url = new URL("www.example.com/file.extension");
然后我会得到一个 InputStream stream = url.openStream();
并用它做一些事情。有没有一种方法,如果我指定 http://www.example.com/
我可以遍历并获取每个文件的所有 url 列表?
最佳答案
有问题的服务器是 Apache 服务器。正如 Nathan 在他的评论中所说,必须启用目录索引。
启用索引
参见:http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/
方法一:
- 打开 Apache 配置文件:(
etc/httpd/httpd.conf
或etc/apache2/apache2.conf
) 添加以下内容:
<Directory /var/www/example.com/directory> Options Indexes FollowSymLinks </Directory>
保存并关闭
- 重启 Apache
方法二:
- 在您要建立索引的目录中创建/打开名为
.htaccess
的文件。 - 附加以下行:
Options Indexes
在 Java 中使用它
现在索引已启用,您实际上可以从 Java 代码访问子目录/文件列表。
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());
这段代码的输出将是
<!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>
根据您的选择解析该 URL。如果您访问 http://www.example.com/directory/
关于java - 在 Java 中通过 HTTP 列出 apache 服务器上的文件/子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32663371/