java - 在servlet中写入文件时出错

标签 java file jsp servlets

我已经通过 servlet 中的 doPost 方法创建了一个文件,但无法向其中写入数据。我不明白是什么错误。顺便说一下,文件正在创建

// TODO Auto-generated method stub
        response.setContentType("text/html");
        String name=request.getParameter("name");
        response.getWriter().println(name);
        File filename= new File("/home/ksampath/D3/DedupeEngine/cache3.txt");
        filename.createNewFile();
        BufferedWriter out = null;
        try
        {
            System.out.println("I am going to create a new file");
            FileWriter fw=new FileWriter("cache3.txt",true);
            out=new BufferedWriter(fw);
            out.write("hello world");
            out.write(name);
        }

        catch(IOException e)
        {
            System.err.println("Error"+ e.getMessage());
        }
        finally
        {
            if(out!=null)
            {
                out.close();
            }
        }
        /*
        System.out.println("Lets us check whether it works");
        PrintWriter writer=response.getWriter();
        writer.println("<h3>hello This is my first servlet</h3>");*/
    }

最佳答案

尝试

FileWriter fw=new FileWriter(filename,true);   //where filename is that File object

public FileWriter(File file, boolean append) throws IOException

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Java Docs

关于java - 在servlet中写入文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978944/

相关文章:

javascript - 我如何获取jsp内Javascript函数的值?

java - Android 深层链接未重定向到 Play 商店

java - 在 Docker 上运行时,Spring Boot 上传功能在生产环境中不起作用

windows - 在 Windows 7 中根据文件路径更改文件名和移动文件

java - 如何将 JSP 变量值传递给此 Struts 标记

java - 我想在单个jsp页面中使用java变量

java - 调用 JooQ DSLContext 的 .close() 时,连接何时关闭(如果有的话)?

java - 这是如何编写此 <class name> <object name > = new constructor name 的正确方法?

Java 归档和高分

c - 文件写入C困惑