Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Object and text file stream code problmes

  1. #1
    Junior Member Kakashi's Avatar
    Join Date
    Oct 2009
    Posts
    29
    My Mood
    Confused
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Object and text file stream code problmes

    My code works fine with one object created by the book constructor and writes to both the object.dat files and the text.dat file, the problem is when I add more than one object, it overwrites (i guess) the file to only include that one object not both. I realy dont know what is going on with this and why its not writing both. The method to wirte the objects to the file works great (well i guess it does not) it does what I want it to do but it doesnt add the new objects to the file just overwirtes the old objects.
    Did i forget some thing when making the object streams?
    import java.io.*;
    import java.util.*;
     
    /**
     * @author Matthew Millar
     * NetBeans 6.7
     * Windows Vista 64bit
     * January 30 2011
     */
    //This program is to test working with object and text data using streams and files
    public class Project1 {
        public static void main(String[] args) throws IOException
        {
            //three books to test prpogram with
            Book book1 = new Book("King Gus","Gus",450,1250.25);
            Book book2 = new Book("Ninja","Kim",780,55.62);
     
            book1.writeTextFile(book1);
            book1.writeObjectFile(book1);
            book2.writeObjectFile(book2);
            book2.writeTextFile(book2);
     
     
     
            try{
            //read in file
            FileInputStream fis = new FileInputStream("Book-text.dat");
            BufferedInputStream bis = new BufferedInputStream(fis);
            DataInputStream dis = new DataInputStream(bis);
     
            // dis.available() returns 0 if the file does not have more lines.
          while (dis.available() != 0) {
     
          // this statement reads the line from the file and print it to
            // the console.
            System.out.println("From Book-Text.dat");
              System.out.println(dis.readLine());
          }
     
          // dispose all the resources after using them.
          fis.close();
          bis.close();
          dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     
     
     
            //read object file
     
             try {
     
                //Construct the ObjectInputStream object
                ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("Book-objects.dat"));
                Object obj = null;
     
                while ((obj = inputStream.readObject()) != null) {
     
                    if (obj instanceof Book) {
     
                        System.out.println("From Book-Object.dat");
                        System.out.println(((Book)obj).toString());
                    }
     
                }
                 inputStream.close();
     
     
            } catch (EOFException ex) { //This exception will be caught when EOF is reached
                System.out.println("End of file reached.");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } 
     
        }
     
    }
     
    //books class
    class Book implements Serializable
    {
        //variables used
        private String title;
        private String author;
        private int numPage;
        private double price;
       //construtor
        //defult no param constructor
        Book(){}
        Book(String t, String a, int n, double p)
            {
                title = t;
                author = a;
                numPage = n;
                price = p;
            }
     
        //get methods
            public String getTitle()
            {
                return title;
            }
            public String getAuthor()
            {
                return author;
            }
            public int getPage()
            {
                return numPage;
            }
            public double getPrice()
            {
                return price;
            }
     
     
            public String toString()
            {
                 return getClass().getName() + "  Title: " + title + ",  Author: " + author + ",  Number of Pages: " + numPage
                + ",  Price: " + price + "\n";
            }
     
     
            //methods for writing files
            public void writeObjectFile(Object obj)
            {
            //write object to file
            try{
             ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("Book-objects.dat"));
             outputStream.writeObject(obj);
     
             System.out.println("Object wrote " + obj);
     
            //clear the output stream
             outputStream.flush();
             outputStream.close();
     
            }catch(IOException ex) {
                ex.printStackTrace();
            }
            }
     
            public void writeTextFile(Object obj)
            {
                try{
                 // Create file
                String textObj = obj.toString();
                FileWriter fstream = new FileWriter("Book-text.dat");
                BufferedWriter out = new BufferedWriter(fstream);
                System.out.println("Write Text File " + obj);
                out.write(textObj);
     
                 //Close the output stream
                 out.close();
                 }catch (Exception e){//Catch exception if any
                     System.err.println("Error: " + e.getMessage());
                }
            }
     
     
     
     
    }//end of book class


  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Object and text file stream code problmes

    I'm not sure where Object Streams stand on appending, but one way to do it could be to add all your objects into an Array List of type Books and then write the Array List to file and when you want to read from the file, add the data back into an ArrayList.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  3. The Following User Says Thank You to newbie For This Useful Post:

    Kakashi (February 3rd, 2011)

  4. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Object and text file stream code problmes

    I believe that the Writer will overwrite the files by default each time. As newbie said, appending might work, but appending will only work for Book-text.bat since BufferedWriter allows appending but ObjectOutputStream does not.

    Basically, you have two options for the ObjectOutputStream:
    1) Try keeping open the ObjectOutputStream throughout the length of the program. That way you will never reopen and rewrite the file.
    2) Try waiting until you are done creating objects and adding all of them at the same time in one method.

    Those are the places I would start. I don't know anything about ObjectOutputStream, but basic IO practices says to try writing the file without closing it between adding lines. If it works, it means the Stream is, by default, erasing all the data before it writes to the file.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Kakashi (February 3rd, 2011)

  6. #4
    Junior Member Kakashi's Avatar
    Join Date
    Oct 2009
    Posts
    29
    My Mood
    Confused
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Object and text file stream code problmes

    Quote Originally Posted by aussiemcgr View Post
    Basically, you have two options for the ObjectOutputStream:
    1) Try keeping open the ObjectOutputStream throughout the length of the program. That way you will never reopen and rewrite the file.
    2) Try waiting until you are done creating objects and adding all of them at the same time in one method.

    .
    I put the file close after all the creation of objets and that worked just right thanks for that tip.

Similar Threads

  1. Object Stream Hanging...
    By Ellipsis in forum Java Networking
    Replies: 2
    Last Post: October 22nd, 2010, 07:20 PM
  2. Open Text file
    By java_kiddy in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: October 5th, 2010, 02:52 AM
  3. insert(embed) a file object (.txt file) in MS excel sheet using java.
    By jyoti.dce in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 12th, 2010, 08:16 AM
  4. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM
  5. Java program to reduce spaces between the words in a text file
    By tyolu in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: May 13th, 2009, 07:17 AM