Results 1 to 6 of 6
  1. #1
    NatProg is offline Member
    Join Date
    Mar 2012
    Posts
    7
    Rep Power
    0

    Default Adding data to an existing binary file

    Could someone help me understand why the recordAdd() doesn't work correctly:
    Thanks in advance


    /*
    Problem Statement:
    works with a binary file; containing data from based on Person class.
    Adds some default data to it. gives the option to add or delete the records.
    find a record based on Person's name or age range

    Overall Plan (step-by-step, how you want the code to make it happen):
    1.Open the file, and add some default records to it
    2.give the user the main menu
    3.based on the user's choice:
    4-add records getting the info from user
    5-Delete records, using a temp file
    6-print records using a loop
    7-Search through records
    8-Find record with name or a specific age range

    Classes needed and Purpose
    Out: main class - intaracts with user, works with the file
    Person: a serializable class to make objects of.
    Date: to manage BD and death dates records
    DateStringToken: to tokenize todays date
    */

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    import java.io.ObjectInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Scanner;
    import java.io.File;
    import java.io.EOFException;

    public class Out {

    private static ObjectOutputStream outputStream = null;
    private static ObjectInputStream inputStream = null;
    private static File fileName = new File ("data.dat");
    private static Person[] person = null;

    public static void main(String[] args)
    {
    Scanner keyboard = new Scanner(System.in);

    //output to file:
    //default records:
    person = new Person[3];
    person[0] = new Person("Johann Sebastian Bach",
    new Date("March", 21, 1685), new Date("July", 28, 1750));
    person[1] = new Person("Igor Stravinsky",
    new Date("June", 17, 1882), new Date("April", 6, 1971));
    person[2] = new Person("John Adams",
    new Date("February", 15, 1947), null);
    openOutputFiles();
    addRecords(person);//adds the default records
    openInputFiles();//opens the input file

    while(true)
    {
    //Menu:
    System.out.println("\n\nMain Menu\n1-Print All Records");
    System.out.println("2-Delete a Record");
    System.out.println("3-Add a record");
    System.out.println("4-Retrieve a record");
    System.out.println("5-Obtain records of a specific age range");
    System.out.println("6-Exit");
    int choice = keyboard.nextInt();
    while(choice < 1 || choice > 6){
    System.out.println("Re-enter");
    choice = keyboard.nextInt();
    }
    switch(choice)
    {
    case 1:
    printRecords();
    break;
    case 2:
    deleteRecord();
    break;
    case 3:
    addRecord();
    break;
    case 4:
    displayRecord();
    break;
    case 5:
    inRangeFinder();
    break;
    default://exits the program
    System.out.println("Exiting ...");
    try {
    inputStream.close();
    outputStream.close();
    } catch (IOException e) {
    System.err.println("Error closing the files!");
    e.printStackTrace();
    }
    System.exit(0);
    }
    }
    }


    public static void inRangeFinder()
    {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter today's date in format of mm/dd/yyyy");
    String date = keyboard.nextLine();
    DateStringToken token = new DateStringToken(date);
    System.out.println("Enter the Max Age:");
    int maxAge = keyboard.nextInt();
    maxAge *= 365;//convert years to days
    System.out.println("Enter the Min Age");
    int minAge = keyboard.nextInt();
    minAge *= 365;//convert years to days
    try
    {
    Person record = null;
    int num;
    while(true)
    {
    record = (Person)inputStream.readObject();
    num = token.daysSinceChrist() - record.daysSinceChrist();//get the difference between their age from Christ's time

    if(!(num > maxAge) && !(num < minAge))
    System.out.println(record.toString());
    }
    }catch(EOFException e){
    System.err.println("Done!");
    } catch (ClassNotFoundException e) {
    System.err.println("Class Not Found Error in inRangeFinder!");
    e.printStackTrace();
    } catch (IOException e) {
    System.err.println("IOException Error on inRangeFinder!");
    e.printStackTrace();
    }
    }

    public static void addRecord()
    {
    Person newPerson = null;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the name:");
    String name = keyboard.nextLine();
    System.out.println("Birthday Info:");
    Date bd = new Date();
    bd.readInput();//gets the birthday info from user
    System.out.println("Death Info:");
    System.out.println("Dead? y/n");
    String answer = keyboard.nextLine();
    if(answer.equals("y"))
    {
    Date death = new Date();
    death.readInput();//gets the death info from user
    newPerson = new Person(name, bd, death);//make the Peron object

    }
    else
    newPerson = new Person(name, bd, null);
    try
    {


    outputStream.writeObject(newPerson);//write the new object to the file
    System.out.println("Record Added!\n\nUpdated Records:\n");
    printRecords();

    }
    catch(IOException e)
    {
    System.out.println("IOException on AddRecord");
    System.exit(0);
    }
    }
    public static void addRecords(Person[] individual)
    {
    //adds the parameter array's abjects to the file
    try
    {
    for(int x = 0; x < individual.length; x++)
    {
    outputStream.writeObject(individual[x]);
    }
    }
    catch(IOException e)
    {
    System.out.println("IOException on AddRecord");
    System.exit(0);
    }
    }


    public static void deleteRecord()
    {
    //deletes a record
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the name of the Person to be deleted: ");
    String name = keyboard.nextLine();
    try
    {
    //open a temp file
    ObjectOutputStream tempFile = new ObjectOutputStream(new FileOutputStream("temp.dat"));
    Person record = null;
    int counter = 0;
    try
    {
    while(true)
    {
    record = (Person) inputStream.readObject();//read an object
    if(!name.equals(record.getName()))//skips if should be deleted
    {
    tempFile.writeObject(record);//copies the record to the temp file
    counter++;
    }
    //System.out.println(counter++);
    }
    }
    catch(EOFException e){
    //do nothing
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    //Closing files for deletation of the old file:
    outputStream.close();
    inputStream.close();
    openOutputFiles();//Make a new file with the same name(replaces)
    openInputFiles();
    try
    {
    //open the temp file for inputing data from.
    ObjectInputStream tempFileRead = new ObjectInputStream(new FileInputStream("temp.dat"));
    for(int y = 0; y < counter; y++)
    {
    outputStream.writeObject(tempFileRead.readObject() );//copies data to the file with the original name
    }
    System.out.println("Done!");
    System.out.println("Updated records:");

    printRecords();//Prints the updated records
    }catch (ClassNotFoundException e) {
    e.printStackTrace();
    }catch(EOFException e){
    //do nothing
    }
    }catch(IOException e)
    {
    System.out.println("ERROR: Delete Record");
    System.exit(0);
    }

    }



    public static void displayRecord()
    {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the name to display the info:");
    String name = keyboard.nextLine();
    Person record = null;
    try
    {
    while(true)
    {
    record = (Person)inputStream.readObject();//gets each record
    if(record.getName().equals(name))//finds and prints out the related record
    System.out.println("found:\n" + record.toString());
    }
    }catch(EOFException e){
    System.out.println("Search Finished!");
    } catch (IOException e) {
    System.err.println("Error IOException");
    } catch (ClassNotFoundException e) {
    System.err.println("Class Not Found Exception");
    }
    }


    public static void printRecords()
    {
    try {
    inputStream.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    openInputFiles();

    //reads the reccords and print on the console
    Person record = null;
    try {
    while(true)
    {
    record = (Person) inputStream.readObject();
    System.out.println(record);
    }
    } catch(EOFException e) {
    return;
    } catch (IOException e) {
    System.out.println("printRecord Exception IOException");
    } catch (ClassNotFoundException e) {
    System.out.println("printRecord Class Not Found Exception");
    }

    }



    public static void openInputFiles()//Opens the input file
    {
    try {
    inputStream = new ObjectInputStream(new FileInputStream(fileName));
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }



    public static void openOutputFiles()
    {
    try
    {
    outputStream = new ObjectOutputStream(new FileOutputStream(fileName, true));
    }
    catch(IOException e)
    {
    System.err.println("Error Opening output File");
    System.exit(0);
    }
    }


    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Adding data to an existing binary file

    Please use [code] tags [/code] when posting code.
    That's not really readable as it stands.

    Also, what does "doesn't work correctly" mean?
    Errors?
    What?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    NatProg is offline Member
    Join Date
    Mar 2012
    Posts
    7
    Rep Power
    0

    Default Re: Adding data to an existing binary file

    Sure. I will next time.
    And well, instead of adding, it erases all the records, and then adds the new record! I need to keep the old data and just add one new record every time I call the addRecord()

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Adding data to an existing binary file

    All you need to do is edit your post and add them.
    If you can't be arsed to do that then why do you expect others to be arsed to look at your problem?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    NatProg is offline Member
    Join Date
    Mar 2012
    Posts
    7
    Rep Power
    0

    Default Re: Adding data to an existing binary file

    Quote Originally Posted by Tolls View Post
    All you need to do is edit your post and add them.
    If you can't be arsed to do that then why do you expect others to be arsed to look at your problem?


    Here you go boss! Let's see if you can help!
    Java Code:
    /*
    Problem Statement: 
    works with a binary file; containing data from based on Person class. 
    Adds some default data to it. gives the option to add or delete the records.
    find a record based on Person's name or age range
    
    Overall Plan (step-by-step, how you want the code to make it happen):
    1.Open the file, and add some default records to it
    2.give the user the main menu
    3.based on the user's choice:
    4-add records getting the info from user
    5-Delete records, using a temp file
    6-print records using a loop
    7-Search through records
    8-Find record with name or a specific age range
    
    Classes needed and Purpose 
    Out: main class - intaracts with user, works with the file
    Person: a serializable class to make objects of.
    Date: to manage BD and death dates records
    DateStringToken: to tokenize todays date
    */
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    import java.io.ObjectInputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Scanner;
    import java.io.File;
    import java.io.EOFException;
    
    public class Out {
    
    private static ObjectOutputStream outputStream = null;
    private static ObjectInputStream inputStream = null;
    private static File fileName = new File ("data.dat");
    private static Person[] person = null;
    
    public static void main(String[] args)
    {
    Scanner keyboard = new Scanner(System.in);
    
    //output to file:
    //default records:
    person = new Person[3];
    person[0] = new Person("Johann Sebastian Bach",
    new Date("March", 21, 1685), new Date("July", 28, 1750));
    person[1] = new Person("Igor Stravinsky",
    new Date("June", 17, 1882), new Date("April", 6, 1971));
    person[2] = new Person("John Adams",
    new Date("February", 15, 1947), null);
    openOutputFiles();
    addRecords(person);//adds the default records
    openInputFiles();//opens the input file
    
    while(true)
    {
    //Menu:
    System.out.println("\n\nMain Menu\n1-Print All Records");
    System.out.println("2-Delete a Record");
    System.out.println("3-Add a record");
    System.out.println("4-Retrieve a record");
    System.out.println("5-Obtain records of a specific age range");
    System.out.println("6-Exit");
    int choice = keyboard.nextInt();
    while(choice < 1 || choice > 6){
    System.out.println("Re-enter");
    choice = keyboard.nextInt();
    }
    switch(choice)
    {
    case 1:
    printRecords();
    break;
    case 2:
    deleteRecord();
    break;
    case 3:
    addRecord();
    break;
    case 4:
    displayRecord();
    break;
    case 5:
    inRangeFinder();
    break;
    default://exits the program
    System.out.println("Exiting ...");
    try {
    inputStream.close();
    outputStream.close();
    } catch (IOException e) {
    System.err.println("Error closing the files!");
    e.printStackTrace();
    }
    System.exit(0);
    }
    }
    }
    
    
    public static void inRangeFinder()
    {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter today's date in format of mm/dd/yyyy");
    String date = keyboard.nextLine();
    DateStringToken token = new DateStringToken(date);
    System.out.println("Enter the Max Age:");
    int maxAge = keyboard.nextInt();
    maxAge *= 365;//convert years to days
    System.out.println("Enter the Min Age");
    int minAge = keyboard.nextInt();
    minAge *= 365;//convert years to days
    try 
    {
    Person record = null;
    int num;
    while(true)
    {
    record = (Person)inputStream.readObject();
    num = token.daysSinceChrist() - record.daysSinceChrist();//get the difference between their age from Christ's time
    
    if(!(num > maxAge) && !(num < minAge))
    System.out.println(record.toString());
    }
    }catch(EOFException e){
    System.err.println("Done!");
    } catch (ClassNotFoundException e) {
    System.err.println("Class Not Found Error in inRangeFinder!");
    e.printStackTrace();
    } catch (IOException e) {
    System.err.println("IOException Error on inRangeFinder!");
    e.printStackTrace();
    }
    }
    
    public static void addRecord()
    {
    Person newPerson = null;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the name:");
    String name = keyboard.nextLine();
    System.out.println("Birthday Info:");
    Date bd = new Date();
    bd.readInput();//gets the birthday info from user
    System.out.println("Death Info:");
    System.out.println("Dead? y/n");
    String answer = keyboard.nextLine();
    if(answer.equals("y"))
    {
    Date death = new Date();
    death.readInput();//gets the death info from user
    newPerson = new Person(name, bd, death);//make the Peron object
    
    }
    else
    newPerson = new Person(name, bd, null);
    try
    {
    
    
    outputStream.writeObject(newPerson);//write the new object to the file
    System.out.println("Record Added!\n\nUpdated Records:\n");
    printRecords();
    
    }
    catch(IOException e)
    {
    System.out.println("IOException on AddRecord");
    System.exit(0);
    }
    }
    public static void addRecords(Person[] individual)
    {
    //adds the parameter array's abjects to the file
    try
    {
    for(int x = 0; x < individual.length; x++)
    {
    outputStream.writeObject(individual[x]);
    }
    }
    catch(IOException e)
    {
    System.out.println("IOException on AddRecord");
    System.exit(0);
    }
    }
    
    
    public static void deleteRecord()
    {
    //deletes a record
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the name of the Person to be deleted: ");
    String name = keyboard.nextLine();
    try
    {
    //open a temp file
    ObjectOutputStream tempFile = new ObjectOutputStream(new FileOutputStream("temp.dat"));
    Person record = null;
    int counter = 0;
    try
    {
    while(true)
    {
    record = (Person) inputStream.readObject();//read an object
    if(!name.equals(record.getName()))//skips if should be deleted
    {
    tempFile.writeObject(record);//copies the record to the temp file
    counter++;
    }
    //System.out.println(counter++);
    }
    }
    catch(EOFException e){
    //do nothing
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    
    //Closing files for deletation of the old file:
    outputStream.close();
    inputStream.close();
    openOutputFiles();//Make a new file with the same name(replaces)
    openInputFiles();
    try
    {
    //open the temp file for inputing data from.
    ObjectInputStream tempFileRead = new ObjectInputStream(new FileInputStream("temp.dat"));
    for(int y = 0; y < counter; y++)
    {
    outputStream.writeObject(tempFileRead.readObject() );//copies data to the file with the original name
    }
    System.out.println("Done!");
    System.out.println("Updated records:");
    
    printRecords();//Prints the updated records
    }catch (ClassNotFoundException e) {
    e.printStackTrace();
    }catch(EOFException e){
    //do nothing
    }
    }catch(IOException e)
    {
    System.out.println("ERROR: Delete Record");
    System.exit(0);
    }
    
    }
    
    
    
    public static void displayRecord()
    {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the name to display the info:");
    String name = keyboard.nextLine();
    Person record = null;
    try
    {
    while(true)
    {
    record = (Person)inputStream.readObject();//gets each record
    if(record.getName().equals(name))//finds and prints out the related record
    System.out.println("found:\n" + record.toString());
    }
    }catch(EOFException e){
    System.out.println("Search Finished!");
    } catch (IOException e) {
    System.err.println("Error IOException");
    } catch (ClassNotFoundException e) {
    System.err.println("Class Not Found Exception");
    }
    }
    
    
    public static void printRecords() 
    {
    try {
    inputStream.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    openInputFiles();
    
    //reads the reccords and print on the console
    Person record = null;
    try {
    while(true)
    {
    record = (Person) inputStream.readObject();
    System.out.println(record);
    }
    } catch(EOFException e)	{
    return;
    } catch (IOException e) {
    System.out.println("printRecord Exception IOException");
    } catch (ClassNotFoundException e) {
    System.out.println("printRecord Class Not Found Exception");
    }
    
    }
    
    
    
    public static void openInputFiles()//Opens the input file
    {
    try {
    inputStream = new ObjectInputStream(new FileInputStream(fileName));
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    
    
    
    public static void openOutputFiles()
    {
    try
    {
    outputStream = new ObjectOutputStream(new FileOutputStream(fileName, true));
    }
    catch(IOException e)
    {
    System.err.println("Error Opening output File");
    System.exit(0);
    }
    }
    
    
    }

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,321
    Rep Power
    25

    Default Re: Adding data to an existing binary file

    Is your code really not indented like you have posted it?

    To append data to an existing file you must use the file output class's constructor with the flag saying you want to append to the file. Otherwise it replaces the existing file.
    Read the API doc to see how to code the constructor.

Similar Threads

  1. How to append data to an already existing file?
    By siteregsam in forum New To Java
    Replies: 3
    Last Post: 05-03-2010, 08:06 PM
  2. Is it possible to insert recorded audio data into an existing file?
    By evan_earnest in forum Threads and Synchronization
    Replies: 1
    Last Post: 01-31-2010, 03:40 AM
  3. Replies: 4
    Last Post: 01-21-2010, 09:31 AM
  4. Adding existing items to a project
    By Katherine in forum Eclipse
    Replies: 4
    Last Post: 01-20-2009, 04:23 AM
  5. Reading Binary File and Changing data
    By janakiram.attuluri in forum Advanced Java
    Replies: 1
    Last Post: 12-21-2007, 10:10 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •