User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 422,662 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 4,683 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 2075 | Replies: 19 | Solved
Reply
Join Date: Apr 2006
Posts: 90
Reputation: KimJack is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
KimJack KimJack is offline Offline
Junior Poster in Training

Parsing a text file

  #1  
Jan 19th, 2008
Hello All,

I am trying to parse a text file with the following type lines:

Mr. Jones has a "dog" and a "cat"


I need to extract the dog and cat and put them into an array of Items.

Here is the set up:
character = read.read();
char first = file.indexOf('\"');
char second = file.indexOf('\"') ;


Here is a snippet of my code:

while(character != EOF)
{
for(int i = 1; i < animal.length; i++)
{

String name1 = animal[i].substring(first, second);

for(int j = 1; i < animal.length; j++)
String name2 = animal[j].substring(first, second);

System.out.println(name1);

System.out.println(name2);
}
}


I am lost on this. Any help would be greatly appreciated.

Thanks
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Sep 2007
Posts: 27
Reputation: schoolsoluction is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 3
schoolsoluction schoolsoluction is offline Offline
Banned

Re: Parsing a text file

  #2  
Jan 20th, 2008
Try the split function of the String class... Split on the " charachter...

If the text does not start with a " you will need all uneven entries of the returning array, otherwise all even entries...

good luck
Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 2,814
Reputation: Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all 
Rep Power: 12
Solved Threads: 281
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is online now Online
Posting Maven

Re: Parsing a text file

  #3  
Jan 20th, 2008
You may also want to consider using the Scanner class with regular expressions.

And once again I'll request:
Please use [ code ] tags to format code in your posts so indentation is preserved.
Last edited by Ezzaral : Jan 20th, 2008 at 11:00 am.
Reply With Quote  
Join Date: Jun 2006
Location: India
Posts: 6,851
Reputation: ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold 
Rep Power: 23
Solved Threads: 344
Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Lazy, Useless & Apathetic

Re: Parsing a text file

  #4  
Jan 20th, 2008
Don't read the file character by character. Always make sure your the I/O operations performed by your program are buffered unless needed otherwise. The less the I/O calls, the better. Instead, read the entire line in a string using BufferedReader / Scanner class and perform the processing. Of the many ways in which the solution can be achieved, regular expressions and manual looping are two of them.

Using the regular expression approach, the regular expression would look something along the lines of: 'Mr. Jones "dog" and "cat" bosh'.match(/[^"]*"([^"]+)"[^"]*"([^"]+)"[^"]*/); This is Javascript, but the concept doesn't change and if you are familiar with regexes you should be able to convert it into a Java equivalent without much effort. If you are not comfortable with regexes, manual looping is the way to go.

Using manual looping, all you would have to do is look for quotes, set a flag, start collecting characters until you find a matching quote, reset the flag and continue the process. The matched data can be stored in a container like ArrayList.

I would personally go with the looping approach due to it's simplicity and extensibility. Plus if this is a homework problem, I am sure your professor would be expecting the looping approach rather than a classy regular expression solution.
I don't accept change. I don't deserve to live.

Happiness corrupts people.

Failing to value the lives of others cheapens your own.
Reply With Quote  
Join Date: Apr 2006
Posts: 90
Reputation: KimJack is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
KimJack KimJack is offline Offline
Junior Poster in Training

Re: Parsing a text file

  #5  
Jan 22nd, 2008
That is interesting, I will give that a try. Thanks
Reply With Quote  
Join Date: Apr 2006
Posts: 90
Reputation: KimJack is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
KimJack KimJack is offline Offline
Junior Poster in Training

Re: Parsing a text file

  #6  
Jan 22nd, 2008
Hello all,

I am trying to use the split function as suggested earlier. I am having a problem and keep getting a NoSuchElementElementException.

Can anyone tell me where my mistakes are?

The file that I am trying to read is in the following format:

Mr. Jones has a "dog" and a "cat"


I need to extract the dog and cat and put them into an array of Items.

Here are some snippets of my code:

while((str = xmlParse.readLine()) != null)
            {
               s = new Scanner (str).useDelimiter("\"");
             
               animal1 = s.next();
               animal2 = s.next();
             
               addItem(animal1, animal2); 
            
            }//while	   



Here is the addItem method:

public void addItem( String animal1, String animal2)
      {      
         pet[count] = new Item(animal1, animal2);
         count++;
      }



Any suggestions would be great and highly appreciated.


Thanks
Last edited by KimJack : Jan 22nd, 2008 at 9:02 pm. Reason: forgot something
Reply With Quote  
Join Date: Jan 2008
Posts: 5
Reputation: jnetpro is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 1
jnetpro's Avatar
jnetpro jnetpro is offline Offline
Newbie Poster

Solution Re: Parsing a text file

  #7  
Jan 22nd, 2008
You could do it like this:
//Read in the file:
java.io.File file = new java.io.File("myfile.txt"); //supply your file name.
java.io.FileReader FR = new java.io.FileReader(file);
StringBuffer buf = new StringBuffer();
int read=0;
try{
   char[] cbuf = new char[1024];
    while ((read  = FR.read(cbuf, 0, cbuf.length)) > -1){
    buf.append(cbuf, 0, read);			
  }
}
catch(Exception ex){
  System.out.println("ex thrown: "+ex);
}
finally{
  FR.close();
}

//Now parse the data read in:
String animalStr = buf.toString();
int q1 = animalStr.indexOf("\"");
if (q1 < 0){
  System.out.println("no animals");
  System.exit(0);
}
int q2 = animalStr.indexOf("\"", q1 + 1);
java.util.ArrayList<String> myAnimals = new java.util.ArrayList<String>();
while (q1 > 0 && q2 > 0){
    String animal = animalStr.substring(q1, q2);
    myAnimals.add(animal);
    q1 = animalStr.indexOf("\"", q2 + 1);
    if (q1 < 0) break;
    q2 = animalStr.indexOf("\"", q1 + 1);
}

//now print out:
for (String myAnimal : myAnimals){
  System.out.println(myAnimal);
}
Reply With Quote  
Join Date: Apr 2006
Posts: 90
Reputation: KimJack is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
KimJack KimJack is offline Offline
Junior Poster in Training

Re: Parsing a text file

  #8  
Jan 23rd, 2008
Thank you for your help. I am trying your suggestion. I am currently getting StringIndexOutOfBoundsException error. Can anyone let me know where I am getting off track?

Here is a snippet of what I am working with:

while((str = xmlParse.readLine()) != null)
            {
                        
               int start = str.indexOf("\"") + 1; 
               int end = str.indexOf( ("\""), start );
            	
               String animal1 = str.substring(start, end);			
                         
               int start2 = str.indexOf(("\""), (end + 1) );
               int end2 = str.indexOf(("\""), start2 + 2);
            
               String animal2 = str.substring(start2, end2);
             				  
               addItem(animal1, animal2);
            }//while	

Thanks for your help
Last edited by KimJack : Jan 23rd, 2008 at 12:07 am. Reason: Prob
Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 2,814
Reputation: Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all 
Rep Power: 12
Solved Threads: 281
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is online now Online
Posting Maven

Re: Parsing a text file

  #9  
Jan 23rd, 2008
Have you looked up what StringIndexOutOfBounds means, the method call that is throwing it and which line it is occurring on? The stack trace will tell you the last two of those. This is just basic debugging that you need to learn to do on your own. The exception message even tells you the index value that was out of bounds and some adding some basic System.out.println() statements can help you know the string and indexes that are causing the problem.

If you continue to have difficulties with it, post back the code, the exact exception message, and exactly what you do not understand about it.
Reply With Quote  
Join Date: Jan 2008
Posts: 5
Reputation: jnetpro is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 1
jnetpro's Avatar
jnetpro jnetpro is offline Offline
Newbie Poster

Solution Re: Parsing a text file

  #10  
Jan 23rd, 2008
String.indexOf throws a StringIndexOutOfBoundsException when either the index parameter is < 0 or > than the length of the String. Hence, make sure to check the indexes before sending them to the indexOf method.

Originally Posted by KimJack View Post
Thank you for your help. I am trying your suggestion. I am currently getting StringIndexOutOfBoundsException error. Can anyone let me know where I am getting off track?

Here is a snippet of what I am working with:

while((str = xmlParse.readLine()) != null)
            {
                        
               int start = str.indexOf("\"") + 1; 
if (start < 0) continue; //check that first quote was found.
               int end = str.indexOf( ("\""), start );
            	
               String animal1 = str.substring(start, end);			
                         
               int start2 = str.indexOf(("\""), (end + 1) );
if (start2 < 0) continue; //check that first quote was found.
               int end2 = str.indexOf(("\""), start2 + 1); //add only 1.
//indexOf would throw a StringIndexOutOfBoundsException if the second parameter
//exceeds the length of the string.
            
               String animal2 = str.substring(start2, end2);
             				  
               addItem(animal1, animal2);
            }//while	

Thanks for your help
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Java Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the Java Forum

All times are GMT -4. The time now is 4:19 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC