java - 在 Java 中通过 HTTP 列出 apache 服务器上的文件/子文件夹

标签 java file http io inputstream

所以我可以使用 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/

方法一:

  1. 打开 Apache 配置文件:(etc/httpd/httpd.confetc/apache2/apache2.conf)
  2. 添加以下内容:

    <Directory /var/www/example.com/directory>
    Options Indexes FollowSymLinks
    </Directory>
    
  3. 保存并关闭

  4. 重启 Apache

方法二:

  1. 在您要建立索引的目录中创建/打开名为 .htaccess 的文件。
  2. 附加以下行: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/

相关文章:

java - 类初始化时创建新线程导致的死锁

java - java中的哪种数据结构可以在恒定时间内添加键/值对并保持按值排序?

java - finally 里面可以用 try catch 吗?

python - 在 python 中使用 glob 不会返回最新的文件路径

javascript - Node.js 异步查找具有相同内容的文件

java - Spring Security 的域权限

c# - 窗口窗体执行批处理文件

python - 简单的 Python 程序卡住了

json - 类型 Undefined 不可分配给类型 [Film]

html - SVG堆栈, anchor 元素和HTTP提取