File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Groovy and the fly likes Closure Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Languages » Groovy
Bookmark "Closure Question" Watch "Closure Question" New topic

Closure Question

Brian Mooney

Joined: Sep 30, 2010
Posts: 3

Have been looking at Groovy recently and am interested in trying to learn it properly.
Was just trying some file manipulation using groovysh and I'm a little puzzled by something that I'm seeing.

I was simply trying to add line numbers to the contents of a file as per:

But when reviewing the output, I'm seeing:
1: 1st Line
2: 2nd Line
3: Some random text
4: Random Stuff
5: Last line
6: Well almost!!

If I update the code as per below (initialising the Integer i to 1 as opposed to 0):

I get the same output:
1: 1st Line
2: 2nd Line
3: Some random text
4: Random Stuff
5: Last line
6: Well almost!!

My question is why doesnt the first code block index the lines from zero?
To get the desired result, I have to edit the code as such:

which results in:
0: 1st Line
1: 2nd Line
2: Some random text
3: Random Stuff
4: Last line
5: Well almost!!

This is of course very trivial but I'm more wondering where my understanding of what is happening is falling down as I would have expected the final result to be produced by the very first code block.

Appreciate any correspondance

Jeanne Boyarsky
internet detective

Joined: May 26, 2003
Posts: 29219

This does what you want. Passing the desired start index as a parameter prevents Groovy from using a default of 1 for the line number.

The eachLine method is defining the second argument to be the line number. It ignores any requests you make of i. For example, if you change i++ to i+=2, you get the same behavior 1-6 as before because eachLine is helpfully setting i to the line number for you.

[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Brian Mooney

Joined: Sep 30, 2010
Posts: 3
Indeed you're right. I was getting confused about the inputs for the eachLine() method.

Appreciate the response and help on the matter.

I agree. Here's the link:
subject: Closure Question
Similar Threads
checking for existence of file
JAR + Saving and Uploading files
Pesudo coding
Removing multiple objects from ArrayList
Regex help