2

So I'm trying to write and read a data file and declare a new variable of type 'GroceryStore' after I read the data file. I keep getting cast exception errors when I'm running my program. Could someone explain to me why this is happening and how I can fix it? Thanks.

Here's my write data file method:

 {
      FileOutputStream file = null;
      ObjectOutputStream outStream = null;
      file = new FileOutputStream(new File(filename));
      outStream = new ObjectOutputStream(file);

      outStream.writeObject(store1);
      System.out.print(filename + " was written\n");

   }

Here's my read data file method

 {
      FileInputStream file = null;
      ObjectInputStream inStream = null;
      file = new FileInputStream(new File(filename));
      inStream = new ObjectInputStream(file);

      GroceryStore newStore = (GroceryStore) inStream.readObject();
      store1 = newStore;
      System.out.print(filename + " was read\n");

     }
Suds2
  • 241
  • 2
  • 5
  • 14

1 Answers1

0

At first glance at the code for reading it seems to want to put it to fast to the class GroseryStore, probably need some parsing before you can get it in there. Try to System.out.println the input from the reader, then you know what you have, then parse / chop and slice that into what you need / want of it.

So, second make a class for the read / write operations. As an example of how the write might work for simple text output file you could use something like this:

private String file_name = "FileName";
private String file_extention = ".txt";

BufferedWriter writer = null;

public void writeTextToFile(String stuff_to_file) {
    // trying to write (and read) is a bit hazardous. So, try, catch and finally
    try {
        File file = new File(file_name + file_extention);

        FileOutputStream mFileOutputStream = new FileOutputStream(file);
        OutputStreamWriter mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream);
        writer = new BufferedWriter(mOutputStreamWriter); 

        writer.write(stuff_to_file); // and finally we do write to file

        // This will output the full path where the file will be written to.
        System.out.println("\nFile made, can be found at: " + file.getCanonicalPath()); 
    } catch (Exception e) { // if something went wrong we like to know it.
        e.printStackTrace();
        System.out.println("Problem with file writing: " + e);
    } finally {
        try { // Close the writer regardless of what happens...
            writer.close();
    } catch (Exception e) { // yes, even this can go wrong
                e.printStackTrace();
            } // close try / catch
        } // close finally
   } // close method