Add file

  • Thread starter JaysFan31
  • Start date
  • #1
JaysFan31

Main Question or Discussion Point

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
 

Answers and Replies

  • #2
chroot
Staff Emeritus
Science Advisor
Gold Member
10,226
34
Well, you should be able to look at your filesystem and see if it created the file! It looks like you're on the right track.

However, I should mention that Java includes a "serialization" mechanism that can automatically save and restore objects to files without any effort from you. You should consider using serialization, unless you have some specific reason it cannot be used.

- Warren
 

Related Threads on Add file

Replies
0
Views
3K
  • Last Post
Replies
2
Views
2K
Replies
4
Views
3K
Replies
4
Views
7K
Replies
7
Views
451
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
12
Views
918
  • Last Post
Replies
10
Views
416
Top