【问题标题】:JSP write to a text fileJSP 写入文本文件
【发布时间】:2012-06-30 05:40:17
【问题描述】:

我正在创建带有提交按钮的 HTML 输入表单。表单操作将我们带到一个 jsp 页面。 我在我的 JSP 页面上写了这个

        ServletContext context = this.getServletContext();

        String path = context.getRealPath("WEB-INF/list.txt");


        User user = new User(fName, lName, eAddress, phone, company, webinar,dateObj);
        UserIO.add(user, path);

然后我创建了一个名为 UserIO 的 java 类

public class UserIO {

    public static void add(User user, String path) throws IOException  
     {
        FileOutputStream fos= new FileOutputStream(path, true);

        PrintWriter out = new PrintWriter(fos);//, true));

        out.println(user.getFname() + "|" + user.getLname() + "|" + user.getEmail() + "|"   );
         out.println(user.getPhone() + "|" + user.getCompany() + "|" + user.getWebinar() + "|" + user.getDate());

        out.close();
    }

}

现在我的问题是,输出显示在 JSP 页面上,但没有保存到文本文件。

我在 Netbeans 中完成了这个程序,并将文件保存在 <projectname>/web/WEB-INF 下。

我尝试将路径更改为<projectname>/web/WEB-INF/list.txt,但给了我错误消息。所以卡住改成上面的了。

告诉我你的专家意见如何解决这个问题?

【问题讨论】:

    标签: jsp text


    【解决方案1】:

    在您的项目 'build\web\WEB-INF\' 目录 () 中查找 txt 文件。 我遇到了同样的问题,然后我在给定目录中找到了文本文件。 :-) 顺便说一句,我的意思是如果您使用的是 Netbeans IDE..

    【讨论】:

      【解决方案2】:

      您必须为 FileOutputStream 提供正确的路径!
      eclipse 目录中是否有任何名为 WEB-INF 的文件夹。我觉得不行!
      尝试使用这些行来了解文件的创建位置:

      File file = new File("list.txt");
      System.out.println(file.getCanonicalFile());
      


      【讨论】:

      • 我在 netbeans 中这样做。当我创建 Java web - 应用程序 - WEB-INF 文件夹被创建。
      • 但我不认为它在 netbeans(应用程序)文件夹中。我相信 WEB-INF 是在您工作区的某个地方创建的,这完全不同。照我说的做,你会看到文件是在哪里创建的。
      【解决方案3】:

      我想,我找到了你的答案:
      尝试使用这个:

      (我假设文件已找到)
      要写入您的文件,您应该使用以下代码替换您的代码:

      FileOutputStream fos= new FileOutputStream(path, true);
      fos.write((user.getFname() + "|" + user.getLname() + "|" + user.getEmail() + "|").getBytes());
      fors.write((user.getPhone() + "|" + user.getCompany() + "|" + user.getWebinar() + "|" + user.getDate()).getBytes());
      


      完成了!

      【讨论】:

        猜你喜欢
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-18
        相关资源
        最近更新 更多