JavaServletでファイル一覧を取得するコードを書いています。
直接、urlを入力してファイル内容を表示することは出来るのですが、ファイル一覧の取得で出来ませんでした。
ファイルオブジェクトは使用できないのでしょうか。
環境
・windows10
・eclipse
・動的web serverプロジェクト
java
1package servlet; 2 3import java.io.File; 4import java.io.IOException; 5 6import javax.servlet.ServletException; 7import javax.servlet.http.HttpServlet; 8import javax.servlet.http.HttpServletRequest; 9import javax.servlet.http.HttpServletResponse; 10 11public class SvFileList extends HttpServlet { 12 13 public void doGet (HttpServletRequest req, HttpServletResponse res) 14 throws ServletException, IOException { 15 16 //url 17 StringBuffer url = req.getRequestURL(); 18 19 //フォルダパス 20 String path = url + "/../resource/"; 21 22 //直接ブラウザに表示することは出来る 23 //String path = url + "/../resource/sampleData_1.txt"; 24 25 //ファイルオブジェクト 26 File dir = new File(path); 27 if(!dir.exists())System.out.println("not exists dir"); 28 29 //ファイル一覧取得 30 for(File f : dir.listFiles()){ 31 System.out.println(f.isFile() + " " + f.getName()); 32 } 33 } 34} 35
追記
ご返信ありがとうございました。
下記でパスを取得してファイルに書き込みを行いましたが、書き込みはできない様ですね。
//オブジェクト取得
ServletContext sc = this.getServletContext();
//ファイルパス
String path = sc.getRealPath("/WEB-INF/resource") + "/test.txt";
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。