Search code examples
javafileprintwriter

(Java) Only last input gets written in file, previous inputs ignored


I'm having trouble making the code to write multiple lines to the CSV file. When I open up the CSV file, only the last input by the user is shown and all the previous inputs are not.

I also can't seem to put the headers at the top of the file to show "Name, Time"

import java.util.*;
import java.io.*;

public class programOneTest
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String choice;
        do
        {
            String fileName = "storage.csv";
            String name = getName(sc);
            double time = getTime(sc);
            writeToFile(fileName, name, time);
            System.out.println("Would you like to enter more data? (Y/N)");
            choice = sc.nextLine();

        } while ("y".equalsIgnoreCase(choice));
    }

    private static String getName(Scanner sc)
    {
        String name;
        do
        {
            System.out.println("Name:");
            name = sc.nextLine();
            if (name.isEmpty()) 
            {
                System.out.println("Error. Please enter a name.");
            }
        } while (name.isEmpty());
        return name;
    }

    private static double getTime(Scanner sc)
    {
        double time = -1.0;
        do
        {
            System.out.println("Time:");
            time = sc.nextDouble();
            sc.nextLine();
            if (time > 0)
            {
                break;
            }
            else
            {
                System.out.println("Error. Please enter an appropriate time.");
            }
            
        } while (time < 0);
        return time;
    }

    private static void writeToFile(String pFileName, String pName, double pTime)
    {
        FileOutputStream fileStrm = null;
        PrintWriter pw;
        try
        {
            fileStrm = new FileOutputStream(pFileName);
            pw = new PrintWriter(fileStrm);
                        pw.println("Name , Time"); //Apparently i cannot do this as it causes errors?
            pw.println(pName + "," + pTime);
            pw.close();
        }
        catch(IOException e)
        {
            System.out.println("Error in writing to file: " + e.getMessage());
        }
    }
}

Output in program:

Name:
John
Time:
6
Would you like to enter more data? (Y/N)
Y
Name: 
Van
Time:
4

What is shown in CSV file:

Van, 4

What I want to be shown in CSV file:

Name, Time
John, 6
Van, 4

Solution

  • You should open the file with append flag "true"

    fileStrm = new FileOutputStream(pFileName, true);
    

    Reference to the documentation