简体   繁体   English

使用Tomcat时无法写入文件

[英]Unable to write a file while using Tomcat

I am unable to create and then write a file in Tomcat. 我无法在Tomcat中创建然后编写文件。 The file gets created if I run the java program (only the writing piece of code) as a Java application , but fails in Tomcat. 如果我将java程序(仅编写代码段)作为Java应用程序运行,则会创建该文件,但在Tomcat中会失败。

there is no error message. 没有错误消息。 The file is simply not created at all! 根本就没有创建该文件!

Please suggest if I am missing something here: 请建议我在这里遗漏一些东西:

//code inside the servlet
public void setData(HttpServletRequest request){
    name=request.getParameter("name");
    address=request.getParameter("address");


    BufferedWriter dataOut;
    try {
        System.out.println("Wrinting file...");
        dataOut = new BufferedWriter(new FileWriter("data.txt", true));




        dataOut.write("name:");
        dataOut.flush();

        dataOut.write("address");
        dataOut.flush();

        dataOut.write("\n");
        dataOut.flush();

        dataOut.close();
        System.out.println("File write complete!");
    }
    catch(Exception e){
        e.printStackTrace();
    }

Looks like the file really is created without problems. 看起来这个文件确实是没有问题的。

You may actually be missing where it is saved. 你实际上可能会丢失在那里保存。

Change this line: 改变这一行:

System.out.println("File write complete!");

To: 至:

System.out.println("File write complete! Saved to: "+new File("data.txt").getAbsolutePath());

And you may solve the mistery. 你可以解决这个错误。

The file is being created, but it is using a relative path. 正在创建文件,但它正在使用相对路径。 It will be created relative to the execution location, which on Tomcat will not be where you're used to it being. 它将对于执行位置创建,在Tomcat上将不会是您习惯的位置。

Use an absolute path or print its location. 使用绝对路径或打印其位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM