add file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PvtBillPilgrim
    New Member
    • May 2007
    • 19

    #1

    add file

    I need to write a method called save that takes a String as a parameter, and returns a boolean value. The parameter represents a filename, and the method should save the contents of one of my classes Flight.java to a file with that filename. I need to include all of the contents created in Flight.java, including the origin and destination airports, as well as an entire list of passengers. I need to able to restore the Flight object and all of its data from the file. Thus, I need to ensure that all of the data gets saved to the file. The method should return true if it is able to save the flight, or false otherwise.

    Here's my code:
    Code:
    public boolean save(String fileName) throws IOException
      {    
        FileWriter fw = new FileWriter (fileName,true);
        BufferedWriter bw = new BufferedWriter (fw);
        PrintWriter outFile = new PrintWriter (bw);    
        outFile.println(FlightNumber);
        outFile.println(OriginalAirport);
        outFile.println(DestinationAirport);
        for (int i = 0; i < numberOfPassengers; i++)
          outFile.println(passengers[i].toString() + "\n");
        outFile.close();    
        return true;    
      }
    It compiles and obviously in the main method, it prints true, but I don't know if it actually creates a file.
    I'm new to this file material and I'm just not sure if this works or not or even if I'm on the right track.

    Thanks.
    Michael
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by PvtBillPilgrim
    It compiles and obviously in the main method, it prints true, but I don't know if it actually creates a file.
    I'm new to this file material and I'm just not sure if this works or not or even if I'm on the right track.

    Thanks.
    Michael
    I think you're doing fine; open a browser or type 'ls' or 'dir' in the directory where
    you created the file and check it out. As far as I can see you're just writing human
    readable text so you can check the content of the file using an ordinary text
    editor.

    Note though that when you save everything again you append the data to the
    already existing file. (check the FileWriter class for that second ctor parameter).

    kind regards,

    Jos

    ps. you might want to check the Serializable interface docs later.

    Comment

    Working...