?
Solved

Reading file contents into an array

Posted on 2006-04-17
11
Medium Priority
?
202 Views
Last Modified: 2010-03-31
Need some help reading a file with contents seperated by a "*" and placing it into an array.

Here is a snippet of the data in the file:

1000 ISLAND, SALAD DRSNG,LOCAL*1 TBSP*25
1000 ISLAND, SALAD DRSNG,REGLR*1 TBSP*60
100% NATURAL CEREAL *1 OZ*135
40% BRAN FLAKES, KELLOGG'S*1 OZ*90

Basically the Format is:     food Descrip * serving size * calories

The twist is I also need to pull the food descrip and make a combo box for it.

I know i need to use StringTokenizer, but I am lost on how to access the file and use it.
0
Comment
Question by:reefcrazed
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 92

Expert Comment

by:objects
ID: 16474597
following shows how to read text from file, line by line

http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html

for each line you can use the split() method to break it into an array

http://javaalmanac.com/egs/java.util.regex/ParseLine.html

or StringTokenizer

http://javaalmanac.com/egs/java.util/ParseString.html
0
 

Author Comment

by:reefcrazed
ID: 16474755
Read over those and did a couple more searches and currently have this code.

            comboBoxLabel = new JLabel( "Choose A Food:" );
            comboPanel.add ( comboBoxLabel );
            String s;
            Vector foodName = new Vector();
            BufferedReader in = new BufferedReader(new FileReader("FoodCalories.txt"));
            while ((s = in.readLine()) != null)
            {
                StringTokenizer st = new StringTokenizer(s, "*");
              foodName.add(st.nextToken());
              foodServSize.add(st.nextToken());
                foodCalories.add(st.nextToken());
            }
            in.close();
            JComboBox comboBox = new JComboBox(foodName);

But I am getting compilation errors, I get an IO Exception file not found. I have imported the file into my project and have verified that its there. Any more suggestions?
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16474782
just do this and see if it works

place FoodCalories.txt on c:\

and then

replace

>>          BufferedReader in = new BufferedReader(new FileReader("FoodCalories.txt"));

with

          BufferedReader in = new BufferedReader(new FileReader("c:\FoodCalories.txt"));
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 92

Expert Comment

by:objects
ID: 16474788
you just need to handle the exacption

          comboBoxLabel = new JLabel( "Choose A Food:" );
          comboPanel.add ( comboBoxLabel );
          String s;
          Vector foodName = new Vector();
          try {
          BufferedReader in = new BufferedReader(new FileReader("FoodCalories.txt"));
          while ((s = in.readLine()) != null)
          {
              StringTokenizer st = new StringTokenizer(s, "*");
             foodName.add(st.nextToken());
             foodServSize.add(st.nextToken());
                foodCalories.add(st.nextToken());
          }
          in.close();
          } catch (IOException ex) {
              ex.printStackTrace();
          }
          JComboBox comboBox = new JComboBox(foodName);
0
 

Author Comment

by:reefcrazed
ID: 16474867
No didn't work like that either shivaspk.

Thanks Objects, added the exception handling and it started compiling. Still having an issue with it though, going to have to do some more reading.
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16474885
yet you are getting the same exception??? even after using exception handling what Objects had provided???

if so now try what i had said previously along with objects code.

place that file on c:\

          comboBoxLabel = new JLabel( "Choose A Food:" );
          comboPanel.add ( comboBoxLabel );
          String s;
          Vector foodName = new Vector();
          try {
          BufferedReader in = new BufferedReader(new FileReader("c:\FoodCalories.txt"));
          while ((s = in.readLine()) != null)
          {
              StringTokenizer st = new StringTokenizer(s, "*");
             foodName.add(st.nextToken());
             foodServSize.add(st.nextToken());
                foodCalories.add(st.nextToken());
          }
          in.close();
          } catch (IOException ex) {
              ex.printStackTrace();
          }
          JComboBox comboBox = new JComboBox(foodName);
0
 

Author Comment

by:reefcrazed
ID: 16474939
No the file not found exception is cleared up sorry. I needed to be more specific in my response.
I am still having an issue with what to do after I read the file.

I added  System.out.println(s); just afer my while statement and get the entire contents of the file outputed.
Now I need to figure out how to create an object store it some where and be able to pull just the foodName to create a comboBox.

I wrote a food class file to create objects with.

// Food Class
public class Food
{
      String food, servSize;
      int calories;
      
      public Food ( String foodItem, String foodServSize, int foodCalories)
      {
            food = foodItem;
            servSize = foodServSize;
            calories = foodCalories;
      }
      
      public void setFood ( String foodItem )
      {
            food = foodItem;
      }
      
      public String getFood()
      {
            return food;
      }
      
      public void setServSize ( String foodServSize )
      {
            servSize = foodServSize;
      }
      
      public String getServSize()
      {
            return servSize;
      }
      
      public void setCalories ( int foodCalories )
      {
            calories = foodCalories;
      }
      
      public int getCalories()
      {
            return calories;
      }
      
      public String toString()
      {
            return getFood() + "\t" + getServSize() + "\t" + getCalories();
      }
}// End Food Class

Not even sure I should use a vector for this as I do not know to much about them, but I will not learn till I do. Anymore help is appreciated.
0
 
LVL 92

Accepted Solution

by:
objects earned 1000 total points
ID: 16474958
try something like,( where foods is a List of Food objects):

          while ((s = in.readLine()) != null)
          {
              StringTokenizer st = new StringTokenizer(s, "*");
              Food food = new Food(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()));
              foods.add(food);
          }
0
 

Author Comment

by:reefcrazed
ID: 16475045
I think you guys have me on the right road, will need to take this back up in the morning. Thanks Guys.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16475663
Or you can also use split () to do it:

String[] array = s.split ( "*" ) ; // assuming you have Java 1.4 or higher
Food food = new Food ( s[0], s[1], Integer.parseInt ( s[2] ) ) ;
foods.add ( food ) ;
0
 

Author Comment

by:reefcrazed
ID: 16484208
Played with that some tonight and tweaked it and its working. Objects, thanks for the assistance.
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month12 days, 15 hours left to enroll

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question