【问题标题】:I do not see the directory created ,while trying from a servlet . Why is that?从 servlet 尝试时,我没有看到创建的目录。这是为什么?
【发布时间】:2013-01-30 22:35:52
【问题描述】:

以下是尝试在该目录中创建目录和文本文件的 servlet。

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String s = request.getServletContext().getRealPath("/");
    PrintWriter out = response.getWriter();
    FileMaker fm  = new FileMaker();
    fm.makeDirectoryTester();
}

在其中创建目录和文本文件的类:

public void makeDirectoryTester() {
    try {
        File f = new File("FlushTester/");
        if(!f.exists()) {
            boolean b = f.mkdir();
            System.out.println("Directory Made (Inside makeDirectoryTester) --> " + b);
            PrintWriter writer = new PrintWriter("FlushTester/TESTER.txt");
            writer.println("This is the first statement");
            writer.println("This is the second statement");
            writer.println("This is the third statement");
            writer.close();
        }
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

问题是布尔值 f.mkdir() 返回 true 但我看不到任何创建的目录或其中的任何文件!这是为什么 ?我使用tomcat作为服务器。这可能是什么原因?

【问题讨论】:

  • 您希望在哪里创建文件?哪个根目录?
  • 你总是犯同样的重大错误。不要那样做。阅读我在您之前的相关问题中发布的链接。至于它是在哪里创建的,只需打印File#getAbsolutePath()。至于具体的功能要求:停止使用getRealPath()File中的相对路径即可。相关说明:stackoverflow.com/questions/2308188/…
  • @BalusC 我没有在我的代码中使用getRealPath()!在我在这里提供的代码中,我正在测试一些东西,但忘记删除它。
  • @BalusC 参考question i asked another day 可以按照我在上面的代码中创建的方式创建目录以便稍后下载吗?

标签: java tomcat servlets


【解决方案1】:

如果您使用File f = new File("FlushTester/");,该文件相对于您的应用程序的起点。对于tomcat,通常是bin 目录。

如果你在其他地方需要它,你应该使用绝对路径(可能以某种方式配置),或者相对于你的 tomcat 的 bin 目录的路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-27
    • 2021-12-11
    • 2021-11-02
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多