G Krishna Sampath
G Krishna Sampath

Reputation: 97

Error in wrting file in servlet

I have created a file from the doPost Method in servlet but I am unable to write the data to it. I could not figured out what is the error. By the way the file is creating

// 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>");*/
    }

Upvotes: 0

Views: 40

Answers (2)

foxt7ot
foxt7ot

Reputation: 2515

Solution provided by @singhakash is correct.

You can either use

FileWriter fw=new FileWriter(filename,true);

and as stated that if second argument is true than bytes will be appended at end.

or you can use getAbsoluteFile()method of File, in this way

FileWriter fw=new FileWriter(filename.getAbsoluteFile());

The getAbsoluteFile()method will return, The absolute abstract pathname denoting the same file or directory as this abstract pathname(JavaDocs)

Upvotes: 1

singhakash
singhakash

Reputation: 7919

Try

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

Upvotes: 1

Related Questions