簡體   English   中英

通過Java中的HTTP列出apache服務器上的文件/子文件夾

[英]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列表?

有問題的服務器是Apache服務器。 正如Nathan在評論中所說,必須啟用目錄索引。

啟用索引

請參閱: http : //www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/

方法1:

  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/還將獲得一個目錄列表作為網頁http://www.example.com/directory/

不能通過http服務器。 如果您在同一台計算機上運行此代碼,則可以使用普通的Java File API

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM