I have written this program but for some reason it isn't appending to the file?

import java.io.*;

public class numbers 
{
    public static void main(String[] args) throws IOException
    {
        FileWriter grades = new FileWriter(new File("grades.txt"));
        String temp = "";
        for (int i=0; i<=100; i+=2)
        {
            temp = String.valueOf(i);
            grades.write(temp);
            grades.write(",");
        }
        grades.close();

        BufferedReader in = new BufferedReader(new FileReader("grades.txt"));
        System.out.println("The output from the grades.txt file: ");

            try
            {
                temp = in.readLine();
                System.out.println(temp);
            }
            catch(IOException ioe)
            {
                 System.err.println("Error: " + ioe.getMessage());
            }

                 in.close();
        FileWriter grades2 = new FileWriter("grades.txt", true);    
        String temp2 = "";
        for (int j=1; j<=100; j+=2)
        {
            temp2 = String.valueOf(j);
            grades2.write(temp2);
            grades2.write(",");
        }
        BufferedReader inn = new BufferedReader(new FileReader("grades.txt"));
        System.out.println("The output from the grades.txt file: ");

        try
        {
            temp2 = inn.readLine();
            System.out.println(temp2);
        }
        catch(IOException ioe)
        {
             System.err.println("Error: " + ioe.getMessage());
        }
        finally
        {
             inn.close();
        }
    }
}

Use code tags when posting code; rad the forum announcements for more details.

Regarding your issue; open the file in append mode. Use the constructor of FileWriter which accepts a boolean parameter for the same. But keep in mind that default/platform encoding is assumed when writing files.

I thought that I was doing that with the following line:

FileWriter grades2 = new FileWriter("grades.txt", true);

??

You are missing a close statement after writing to the grades2 object.

Thank you kramerd, that was an excellent spot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.