[英]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/
etc/httpd/httpd.conf
或etc/apache2/apache2.conf
) 添加以下內容:
<Directory /var/www/example.com/directory> Options Indexes FollowSymLinks </Directory>
保存並關閉
.htaccess
的文件。 Options Indexes
現在啟用了索引,您實際上可以從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.