在 Java 中通过 HTTP 在 apache 服务器上列出 files/subfolders
List files/subfolders on apache server via HTTP in Java
所以我可以使用
通过 HTTP 访问文件
URL url = new URL("www.example.com/file.extension");
然后我会得到一个 InputStream stream = url.openStream();
并用它做一些事情。有没有一种方法,如果我指定 http://www.example.com/
我可以遍历并获取每个文件的所有 url 列表?
不是通过 http 服务器。如果你是 运行 这在同一台机器上,你可以使用正常的 Java File API.
有问题的服务器是 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
方法二:
- Create/Open 您要索引的目录中名为
.htaccess
的文件。
- 添加以下行:
Options Indexes
在Java
中使用这个
现在索引已启用,您实际上可以从 java 代码访问 subdirectories/files 的列表。
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/
,您还将获得一个目录列表作为网页
所以我可以使用
通过 HTTP 访问文件URL url = new URL("www.example.com/file.extension");
然后我会得到一个 InputStream stream = url.openStream();
并用它做一些事情。有没有一种方法,如果我指定 http://www.example.com/
我可以遍历并获取每个文件的所有 url 列表?
不是通过 http 服务器。如果你是 运行 这在同一台机器上,你可以使用正常的 Java File API.
有问题的服务器是 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
方法二:
- Create/Open 您要索引的目录中名为
.htaccess
的文件。 - 添加以下行:
Options Indexes
在Java
中使用这个现在索引已启用,您实际上可以从 java 代码访问 subdirectories/files 的列表。
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/