Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Overwrite CSV file

807598Apr 12 2006 — edited Apr 12 2006
This should be a basic concept. I know I've done it before, but it's been a few years.

I have data in a CSV file. When I save the new data to the file, it will append all of the data (new & old) to the old CSV file.

Do I need to make a temporary file and then overwrite the old one?

Is there some way to erase the data in a CSV file prior to outputting the new data?

Is there something simple I am missing? I'll continue to look for the answer hoping it will be a quick fix.

Thanks
    
public void exportTable()
{
    //This line added to the example
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    try
    {
        //System.out.println("Exporting Table ");
        //Erase current data in file
        //???

        File file = new File("upcoming.csv");
        String data;
        
        if (file != null)
        {
            try
            {
                    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file,true));
                    PrintWriter fileWriter = new PrintWriter(bufferedWriter);
                   
                    //System.out.println("Exporting Data ");
                    for(int i=0; i < model.getRowCount(); ++i)
                    {
                            for(int j=0; j < model.getColumnCount(); ++j)
                            {
                                    data = model.getValueAt(i,j).toString();
                                    fileWriter.print(data+",");
                            }
                            fileWriter.println("");
                    }       
                    fileWriter.close();
            //System.out.println("Done.... ");
            System.out.println("File saved - upcoming.csv");
        }
        catch(Exception e)
        {
                    JOptionPane.showMessageDialog(null, "Error "+e);
        }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 10 2006
Added on Apr 12 2006
3 comments
866 views