ganvartin
ganvartin

Reputation: 35

Writing Variables using Beanshell Sampler in JMeter into a txt/csv file

My requirement is to write two values using 2 Beanshell Samplers used in different steps, in a single line and separated by a comma But the second variable is written on a new line

I have two different Beanshell Samplers at different steps. First one captures Variable 1 and writes it in a file Second one captures Variable 2 and writes it in the file

First Code:

String path= FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt";
SubmissionNum= vars.get("CP_SubmissionNumber");
EMailID= vars.get("P_emailID");
f = new FileOutputStream(path, true);
p = new PrintStream(f);
this.interpreter.setOut(p); 
p.println(EMailID+","+SubmissionNum);
f.close();

Second Code:

String path= FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt";
Policynumber= vars.get("CP_Policynumber");
f = new FileOutputStream(path, true); 
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(","+Policynumber);
f.close();

Expected Result:

 [email protected],12345601,12345602

Actual Result:

 [email protected],12345601

 ,12345602

Upvotes: 0

Views: 3097

Answers (3)

Dmitri T
Dmitri T

Reputation: 168002

First of all, are you aware of Sample Variables property and Flexible File Writer? If you run your script with multiple virtual users most probably you will suffer from a form of a race condition when multiple threads will be simultaneously writing into the same file resulting in garbage data


Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for any scripting tasks, the reasons are in:

  1. Groovy is compatible with modern Java versions and with Beanshell you're stuck at Java 5 language level
  2. Groovy has much better performance than Beanshell
  3. Groovy has a lot of enhancements making your life easier

For example your code can be shortened as:

  • First:

    def file = new File(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt")
    file << vars.get("P_emailID") << "," << vars.get("CP_SubmissionNumber") << ","
    
  • Second:

    def file = new File(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt")
    file << vars.get("CP_Policynumber") << System.getProperty("line.separator")
    

Upvotes: 0

Ori Marko
Ori Marko

Reputation: 58774

Instead of println which adds new line use print

 p.print(EMailID+","+SubmissionNum);

Upvotes: 1

A P
A P

Reputation: 196

String path= FileServer.getFileServer().getBaseDir() + "//P_IssuePolicy.txt";
SubmissionNum= vars.get("CP_SubmissionNumber");
EMailID= vars.get("P_emailID");
Policynumber= vars.get("CP_Policynumber");
f = new FileOutputStream(path, true);
p = new PrintStream(f);
this.interpreter.setOut(p);
p.println(EMailID+","+SubmissionNum+","+Policynumber);
f.close();

Give it a try with above.

Upvotes: 1

Related Questions