'How to make table structure in csv file when using org.apache.commons.io.FileUtils.writeStringToFile(file)?

I used Webdriver sampler and write selenium -Javascript. Now I used org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('result.csv'), 'myresultdata', 'UTF-8', true) function to write a file . I want to save a tabular data (column & row-wise means one column header and multiple row data) in that file using writeStringToFile() function.is there any other way to write in a csv or xlsx file? How we can achieve this?



Solution 1:[1]

Your myresultdata should have the "table structure" inside it, i.e. columns should be separated by commas (or other separators) and there should be a line break in the end of every "row"

var newline = java.lang.System.getProperty('line.separator')
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('result.csv'), 'header1,header2' + newline, 'UTF-8', true)
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('result.csv'), 'value1,value2' + newline, 'UTF-8', true)
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('result.csv'), 'value3,value4', 'UTF-8', true)

it will generate the result.csv file looking like:

header1,header2
value1,value2
value3,value4

which can be imported into Excel or equivalent without any issues

Also you might want to reconsider your approach, in case of running your test with > 1 thread (virtual user) you will run into a race condition when 2 or more threads will be concurrently writing into the same file so it makes sense to migrate to Flexible File Writer listener

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitri T