【问题标题】:issue with having java in a tomcat servlet edit a .txt file在 tomcat servlet 中使用 java 编辑 .txt 文件的问题
【发布时间】:2012-12-15 02:33:16
【问题描述】:

大家好,我正在尝试让我的代码运行一次;它将插入到 WebContent 目录中已经制作的 .txt 文档中。我在 Apache Tomcat v7.0 中运行 - 在 Eclispe 中构建。

代码:

  public static void insertWinner(String winner) throws IOException{

        String filename= "Winner.txt";
        FileWriter fw = new FileWriter(filename,true); //the true will append the new data
        fw.write("Winner is" + winner);//appends the string to the file
        fw.close();

    }

这是在一个名为 BandIO 的 java 文件中完成的,servlet BandListServ.java 调用该文件将字符串值插入到上述代码中。

当我这样做时没有任何反应,也不知道为什么。

如果您需要任何其他信息,请告诉我,再次感谢!

编辑

我改成这个-

public static void insertWinner(String winner) throws IOException{


        FileWriter out = new FileWriter("Winner.txt");
        out.write("Hello");
        out.close();
        out = new FileWriter("Winner.txt", true);
        out.write(", world!");
        out.close();

    }

编辑:

好的,所以我在 servlet 文件中尝试了这个,但没有 cigar..

             response.setContentType("text/html");


             String filename = "Winner.txt";

             ServletContext context = getServletContext();


             InputStream is = context.getResourceAsStream(filename);
             if (is != null) {
                 InputStreamReader isr = new InputStreamReader(is);
                 BufferedReader reader = new BufferedReader(isr);
                 PrintWriter writer = response.getWriter();
                 String text = "Winner is";


                 while ((text = reader.readLine()) != null) {
                     writer.println(text);
                 }
             }

【问题讨论】:

    标签: java apache jakarta-ee tomcat


    【解决方案1】:

    原则上对文件系统的访问是通过

    File file = getServletContext().getRealPath("/Winner.txt");
    

    此文件可能为空,即当 web 应用程序部署为 .war(so zip 格式),并且 web 服务器未配置为解压 war。

    在您的情况下,文件可能存在并发问题,需要一些锁定。也许你应该使用数据库表。

    同样在下一次部署时,文件可能会丢失。

    【讨论】:

    • 好吧,我只是想通过一个不是 servlet 本身的 .java 文件来访问该文件,因此 getServletContext() 不起作用...
    • 但是不能使用相对路径,而且网页内容目录只能通过ServletContext知道。例如,您可以在属性文件中配置硬完整路径。
    • 您需要将ServletContext 的对象引用传递给该方法。看看 SO 线程 - stackoverflow.com/questions/2728877/…
    • 在最后编辑InputStream is = new FileInputStream(context.getRealPath("/Winner.txt"));
    猜你喜欢
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多