Forum Discussion

indraniria's avatar
indraniria
Contributor
2 years ago

How to use "break in the following loop?

for(File file: f.listFiles())
{
if (file.getName().contains(date_time) ||file.getName().contains(next_day)){
file.eachLine{line ->
if(line.contains(text)){
log.info file.getName()

break
}
}
}

 

Getting below error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 23: the break statement is only allowed inside loops or switches
@ line 23, column 5.
break
^
}

1 Reply

  • ChrisAdams's avatar
    ChrisAdams
    Champion Level 3

    Hi,

    Don't use for-each loop.  Instead, use a 'traditional' for loop or while loop.  I've wrote a second version in your other recent question to stop at the first instance of the string being found.  That includes a for loop with a break statement.

    I cheated slightly in the other solution by reading the contents of the entire file into a single string.

    In your example above, you would need two break statements, one for each loop.  You might find it easier and more readable to split into functions.