user3335456
user3335456

Reputation: 7

Data gets erased during Output stream

So I'm writing a program that will accept the name of a game, the publisher, and the price(as a string) back into a file that has some records in it already. However, when I run the program it erases the previous records.

      //open the output stream
      FileWriter writeFile = new FileWriter(inFile);
      BufferedWriter lineWriter = new BufferedWriter(writeFile);
      PrintWriter printLine = new PrintWriter(lineWriter);

if (menuItem == ADD_GAME)
{    //Get game
      System.out.print("Enter name of game:  ");
      gameName = Keyboard.readString();

      //get publisher
      System.out.print("Enter name of publisher:  ");
      publisherName = Keyboard.readString();

      //get price of game
      System.out.print("Enter game price:  ");
      gamePrice = Keyboard.readString();

      //add game to games
      createdGame.addGame(gameName, publisherName, gamePrice);

      //add game to file record
      outLine = gameName + " " + publisherName + " " + gamePrice;
      printLine.println(outLine);
}

Upvotes: 1

Views: 35

Answers (1)

You are opening the file for overwrite rather than appending. You want to change your FileWriter initialization to:

FileWriter writeFile = new FileWriter(inFile, true);

Upvotes: 2

Related Questions