1

In java 8, this code runs perfectly:

     Stream<String> lines = Files.lines(outfile) {
     List<String> replaced = lines
         .map(line ->
             line.replaceAll('date1', "$newdate1"))
         .collect(Collectors.toList())
     Files.write(outfile, replaced)
 }

In groovy, because I am using a groovy version previous to the 2.6, it doesn't. I cannot change it, is the one used in Katalon. I receive an error "unexpected token ->"

I have tried to enclose the lambda function with brackets these 2 ways, but none works:

    Stream<String> lines = Files.lines(outfile) {
             List<String> replaced = lines
                 .map({line ->
                line}.replaceAll('date1', "$newdate1"))
            .collect(Collectors.toList())
        Files.write(outfile, replaced)
}

and

    Stream<String> lines = Files.lines(outfile) {
    List<String> replaced = lines
        .map({line -> 
                line.replaceAll('date1', "$newdate1")})
        .collect(Collectors.toList())
    Files.write(outfile, replaced)
 }

This wrapping kind of isolate/takes out of context line, that is not recognized as a String, and replaceAll is not working.

I don't know what is the right way to do it, to make it work.

Rumit Patel
  • 8,830
  • 18
  • 51
  • 70
spr654
  • 11
  • 1
  • Your first way is neither valid Java nor valid Groovy. And I can't understand what is wrong with second variant. How can `replaceAll` not work if it's called? Are you sure your arguments are correct? – M. Prokhorov Apr 26 '19 at 13:38
  • Here's [an article](https://mrhaki.blogspot.com/2015/04/groovy-goodness-use-closures-as-java.html) that might help - it has an example of how to use Groovy closures in Java. – M. Prokhorov Apr 26 '19 at 13:51
  • 2
    The Groovy version of that: `Files.lines(outputFile)*.replaceAll(...)` – cfrick Apr 27 '19 at 06:24
  • thanks for this answer – spr654 May 02 '19 at 14:19

2 Answers2

1

You've got extra curly brackets in Java and Groovy that's why it wasn't working

List<String> lines = Files.lines(outputFile)
                .map({ line -> line.replaceAll('date1', "$newdate1") })
                .collect(Collectors.toList())
Files.write(outputFile, lines)
Adrian
  • 2,984
  • 15
  • 27
0

I finally found a very simple solution (pure groovy):

'convert input file into text'
fileText = infile.text

'Replace the value date1 with newdate1'
fileText = fileText.replaceAll('date1', "$newdate1")

'then send the text to the output file'
outfile << fileText
barbsan
  • 3,418
  • 11
  • 21
  • 28
spr654
  • 11
  • 1