unable to append to file using printwriter in java

2019-08-28 20:50发布

问题:

I have the following code to initialise a printwriter object--

/* This function is used to initialise the printwriter element so that it can begin the task of writing data into assignor.txt file...
     * 
     */
    public void startwriterassignor(String filename, boolean appendToFile) {

        //pw = null;

        try 
        {

            if (appendToFile== true) 
            {

                    //If the file already exists, start writing at the end of it.
                    pw = new PrintWriter(new FileWriter(filename, true));

            }
            else {

                    pw = new PrintWriter(new FileWriter(filename, false));
                    //  this is equal to:
                    //  pw = new PrintWriter(new FileWriter(filename, false));

            }
            //pw.flush();

        }
        catch (IOException e) {
                e.printStackTrace();
        }

}

First I invoke the above function using the call below--

startwriterassignor("assignor.txt", false);

After writing some data to the file I again invoke same function using call below-

startwriterassignor("assignor.txt", true);

After the second call to 'startiwriterassignor', more data is written (appended) into the file. However new data is not being appended to the file assignor.txt, how do I rectify this error?