-2

i have written codes to generate random ID and store to file. then send the data which data contains the stored ID. Then I set it to loop 3 times. The data sent sucessfully 3 times, but there is only one file and contains LAST ID only. I wanted to have 3 files, named 1,2,3.

for (int i = 1; i <= 3; i++) {
//test data using dynamic Id at order Id
String RandomOrderId = CustomKeywords.'test.RandomStringUUID.getUuid'()
println(RandomOrderId)

//store the OrderId to file
def OrderId = new File(RunConfiguration.getProjectDir() + "/Data Files/OrderId.txt")
OrderId .newWriter().withWriter { it << RandomOrderId }
println OrderId.text

def exceldata = CustomKeywords.'test.excelfile.ReadExcelData'('Data Files/1.xlsx', 'testdata', 'Test case1', 'Json Data 1')
exceldata = exceldata.replace("<OrderId>", OrderId.text)
        
Order.Message('message',exceldata)

}
user2201789
  • 1,083
  • 2
  • 20
  • 45

1 Answers1

0

the problem that File.newWriter() overwrites content of the file.

replace this line:

OrderId.newWriter().withWriter { it << RandomOrderId }

with the following one:

OrderId.newWriter(true).withWriter { it << RandomOrderId << '\n' }

or with:

OrderId.withWriterAppend{ it << RandomOrderId << '\n' }

or with:

OrderId.append( RandomOrderId + '\n' )

read more about file methods here: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html

daggett
  • 26,404
  • 3
  • 40
  • 56
  • i tried this OrderId.newWriter(true).withWriter { it << RandomOrderId << '\n' } the result is still one file, content has appended data. how do i overwrite the old data? I read the BufferedWriter ref doc, could not find a suitable one. – user2201789 Aug 19 '20 at 05:22
  • one file is fine. @daggett – user2201789 Aug 20 '20 at 02:12
  • move `for` loop inside the `newWriter(false).withWriter{ ... }` closure – daggett Aug 21 '20 at 00:19