Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何动态获取文件夹的路径_Java_Servlets - Fatal编程技术网

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

Java 如何动态获取文件夹的路径,java,servlets,Java,Servlets,我试图在项目路径中的文件夹下列出文件,我正在使用java servlet 我是这样做的:folder=new field:/Vivek/Touchpoint/MirrorImage/WebContent/Image/,我希望这条路径是动态的,因为将来我将在其他系统上部署它,所以必须采用这条路径 我尝试过InputStream input=getServletContext.getResourceAsStreamD:/Vivek/Touchpoint/MirrorImage/WebContent/

我试图在项目路径中的文件夹下列出文件,我正在使用java servlet

我是这样做的:folder=new field:/Vivek/Touchpoint/MirrorImage/WebContent/Image/,我希望这条路径是动态的,因为将来我将在其他系统上部署它,所以必须采用这条路径

我尝试过InputStream input=getServletContext.getResourceAsStreamD:/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.printlnnew文件..getAbsolutePath;但它会打印C:\Windows\system32\。

您可以尝试以下方法:

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

是的,这是可行的,我对这个问题有点怀疑。你能帮我一些方法吗?我会用我的代码来做self@viveksingh好的。如果你有空的话,我必须根据我得到的上述数据制作一个JSONexplain@viveksingh你是说文件列表?@viveksingh目录树?