簡體   English   中英

如何動態獲取文件夾的路徑

[英]How to Dynamically get the path of a folder

我正在嘗試在我的項目路徑中的文件夾下列出文件,我正在使用java Servlets

我正在像這樣File folder = new File("D:/Vivek/Touchpoint/MirrorImage/WebContent/Image/"); ,我想使該路徑動態化,因為將來我將在其他系統上部署它,因此必須采用該路徑

我已經嘗試過InputStream input = getServletContext().getResourceAsStream("D:/Vivek/Touchpoint/MirrorImage/WebContent/Image"); ,但是從InputStream開始,我無法在之后循環

我正在做這樣的整個代碼

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
             String DirectoryName="";
                File folder = new File("D:/Vivek/Touchpoint/MirrorImage/WebContent/Image/"); // Setting the path manually 
                File[] listOfFiles = folder.listFiles(); //creating an array to loop through
            //  System.out.println(folder);

                for (int i = 0; i < listOfFiles.length; i++) {
                  if (listOfFiles[i].isFile()) {
                 //   System.out.println("File " + listOfFiles[i].getName());
                  } else if (listOfFiles[i].isDirectory()) {
                     test=listOfFiles[i].getName();
                     System.out.println("Directory " + DirectoryName);
                  }

                }


}

這個
是我的項目結構

我已經嘗試過System.out.println(new File(".").getAbsolutePath()); 但它顯示C:\\Windows\\system32\\.

您可以嘗試如下操作:

String path = request.getServletContext().getRealPath("/Image");
File folder = new File(path);
...

暫無
暫無

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

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