Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Change the contents of a file into a string

  1. Jun 22, 2007 #1
    Hi. I'm in an elementary Java course and I wrote the following code to print the contents of a file I created earlier:

    Code (Text):

    public static void load(String fileName) throws IOException
      {    
        try
        {      
          Scanner fileScan = new Scanner(new File(fileName));      
          while (fileScan.hasNext())
          {
            System.out.println(fileScan.nextLine());
          }
        }        
        catch (FileNotFoundException exception)
          {
            System.out.println("The file was not found.");
          }
      }
     
    It prints (correctly) the following lines of the file:
    Flight Number: 1234
    From: Lester B. Pearson International Airport (YYZ): Toronto, Ontario
    To: Not Set
    7 passenger(s):

    Name: Roy Halladay
    Age: 30

    Name: AJ Burnett
    Age: 30

    Name: Dustin McGowan
    Age: 25

    Name: Shaun Marcum
    Age: 25

    Name: Josh Towers
    Age: 30

    Name: Casey Janssen
    Age: 25

    Name: Jeremy Accardo
    Age: 25

    This represents a particular flight in a class I wrote before. I need to use this information to create a Flight object. I just need to know if there is an easy way to transform (using elementary Java code) all this information into a String so that I can get particular aspects of it. Basically, I need to get the flight number "1234" as a String. I need to get the original airport etc as Strings. Can I do this?
     
  2. jcsd
  3. Jun 22, 2007 #2
    Is there some way in java to search for a certain element? If so, you could search for the ": " that you have in front of each data item you (I think) are looking for. Anyway, just a random idea. Have a nice day.
     
  4. Jun 22, 2007 #3

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    fileScan.nextLine() is already a String.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Change the contents of a file into a string
Loading...