如何动态获取文件夹的路径

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);
...