Reputation: 41
I'm parsing output for a test I'm running as a Gradle JavaExec task. I want to filter the output so that only errors are shown in stdout (I'm running the task from the Windows command line).
In a doLast{}
block, I've parsed the OutputStream to a list of strings where each entry is a line:
ByteArrayOutputStream baos = new ByteArrayOutputStream()
String log = baos.toString()
List<String> logLines
logLines = new ArrayList<String>(Arrays.asList(log.split('\n')))
then iterated through the list, printing each line that starts with 'E' (for ERROR):
for (String entry : logLines){
if (entry.charAt(0) == 'E'){
println "First char == E"
println (entry)
}
}
println "Execution complete!"
My output prints the first two errors, but prints empty strings for all the rest:
First char == E
ERROR More info here
First char == E
ERROR More info here
First char == E
First char == E
First char == E
Execution complete!
Why does println(entry)
print empty strings? Obviously entry
is not an empty string, because it wouldn't get past the boolean condition if it's first character was empty.
Upvotes: 3
Views: 1221
Reputation: 41
@Roman had the answer: println(groovy.json.JsonOutput.toJson(entry))
revealed that carriage returns \r were being used in addition to new lines \n. Therefore the solution is to split by the regex '[\r\n]+' which will separate into an array of strings at each \n or \r\n
Upvotes: 1