DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert CSV to XML in Java
  • How to Convert XLSX to CSV in Java
  • Java UDFs and Stored Procedures for Data Engineers: A Hands-On Guide
  • Using Java Class Extension Library for Data-Oriented Programming - Part 2

Trending

  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  1. DZone
  2. Data Engineering
  3. Data
  4. Saving Data to CSV Files With Java Through JMeter

Saving Data to CSV Files With Java Through JMeter

Wish you could complete your entire CSV file process in one place? Let's see how you can create and update CSVs through JMeter.

By 
Michal Borenstein user avatar
Michal Borenstein
·
Sep. 25, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
24.7K Views

Join the DZone community and get the full member experience.

Join For Free

Creating CSV files with Java through Apache JMeter is a convenient and easy way to form and to update your CSV files. Instead of creating the CSV file separately, you can complete your whole work process in one place — in JMeter. In this blog post, I will show you how to read and write CSV files through JMeter, and how to save data with them. This should be part of a longer test script you have, which uses the data from the CSV file for the load testing scenario.

Let’s get started.

1. First add a Thread Group

Right click on Test Plan -> Threads -> Thread Group

2. Add an element that enables you to write a code in Java, i.e a BeanShell element. This can be a Sampler, PreProcessor or PostProcessor, according to your script needs. In this example, we will use a sampler.

Right click on Thread Group -> Sampler -> BeanShell Sampler

This is where you add the Java code with all the relevant parameters for the CSV file. The code executes writing to a CSV file with the variables in it.

Image title

This is the code I used. This code writes the parameters that you set to a CSV file. Every time the sampler is executed, one more line is added to the CSV file.

import java.io.FileWriter;
import java.util.Arrays;
import java.io.Writer;
import java.util.List;

//Default separator
char SEPARATOR = ',';

//function write line in csv
public void writeLine(FileWriter writer, String[] params, char separator) {
    boolean firstParam = true;

    StringBuilder stringBuilder = new StringBuilder();
    String param = "";

    for (int i = 0; i < params.length; i++) {
        //get param
        param = params[i];
        log.info(param);

        //if the first param in the line, separator is not needed
        if (!firstParam) {
            stringBuilder.append(separator);
        }

        //Add param to line
        stringBuilder.append(param);

        firstParam = false;
    }

    //prepare file to next line
    stringBuilder.append("\n");

    //add to file the line
    log.info(stringBuilder.toString());
    writer.append(stringBuilder.toString());

}

//get path of csv file (creates new one if its not exists)
String csvFile = "<path to csv file>"; // for example '/User/Downloads/blabla.csv'

String[] params = {
    $ {
        param1
    },
    $ {
        param2
    },
    $ {
        param3
    }
};

FileWriter fileWriter = new FileWriter(csvFile, true);
writeLine(fileWriter, params, SEPARATOR);

//proper close to file
fileWriter.flush();
fileWriter.close();


If you want to use it, you can adjust the following lines:

  • Change the parameters here, and add more if you need to:
String[] params = {${param1}, ${param2}, ${param3}};



  • If you run this script a few times, “true” will append new lines to the file. To override the existing lines, change to “false”. This is an optional part of the code.
FileWriter fileWriter = new FileWriter(csvFile, true);



4. Add a BeanShell element that will read the entire CSV file and set each parameter to a variable so they can be used later on in the script.

Here is an optional script for reading the entire file, you can create your own.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

String csvFile = "<path to csv file>";
BufferedReader bufferedReader = null;
String line = "";
String SEPARATOR = ",";

try {
    bufferedReader = new BufferedReader(new FileReader(csvFile));

    int counter = 1;
    while ((line = bufferedReader.readLine()) != null) 
    {
            String[] items = line.split(SEPARATOR);

for(int i = 0; i < items.length; i++)
{
vars.put(“param” + i + counter, items[i] );
} 
    }

} 
catch (FileNotFoundException e) 
{
  e.printStackTrace();
} 
catch (IOException e) 
{
  e.printStackTrace();
} 
finally {
  if (bufferedReader != null) {
      try {
          bufferedReader.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

}



Let's explain some of the lines:


  • The following line goes through each line in the CSV file and reads it.


while ((line = bufferedReader.readLine()) != null) 



  • The following defines the array of the CSV line's params.


String[] items = line.split(SEPARATOR); 



  • The following part sets a new JMeter variable for each parameter in the line. You can define the parameters according to your needs and decide what to do with them in JMeter.


items.length; i++)
{
vars.put(“param” + i + counter, items[i] );
} 



That’s it! Now you can incorporate this configuration into your entire script, and integrate the CSV file reading and writing into your complete test flow.


That’s it! You now know how to read and write data to CSV files through JMeter in Java.

CSV Java (programming language) Data (computing)

Published at DZone with permission of Michal Borenstein, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert CSV to XML in Java
  • How to Convert XLSX to CSV in Java
  • Java UDFs and Stored Procedures for Data Engineers: A Hands-On Guide
  • Using Java Class Extension Library for Data-Oriented Programming - Part 2

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!