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

时间:2019-06-06 10:57:30

标签: java servlets

我正在尝试在项目路径下的文件夹下列出文件,我正在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);
                  }

                }


}

This
是我的项目结构

我尝试过System.out.println(new File(".").getAbsolutePath());,但它会打印C:\Windows\system32\.

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

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