Search code examples
splitjmeterbeanshell

How to use Split for string in Beanshell?


I'm writing a Beanshell sampler in JMeter to read a file, in which I want to split each line by comma(,) and want to extract the values. I'm getting the first splitted string with index 0 but for next values with index 1, 2 and so... it is not giving the values.

value = value.append(line.split(",")[2]);

Here, for index 0 it is working all fine BUT for index more than 0, it fails.


Solution

  • Are you sure that your line.split(",") expression produces String array with length > 1? How do you know?

    For instance the next code:

    String line = "quick, brown, fox, jumped, over";
    String[] words = line.split(",");
    for (int i = 0; i < words.length; i++) {
      log.info(words[i]);
      if (i == 2) {
          log.info("Third word is: " + words[2]);
      }
    }
    

    Produces the following output:

    2014/10/08 13:17:37 INFO  - jmeter.util.BeanShellTestElement: quick 
    2014/10/08 13:17:37 INFO  - jmeter.util.BeanShellTestElement:  brown 
    2014/10/08 13:17:37 INFO  - jmeter.util.BeanShellTestElement:  fox 
    2014/10/08 13:17:37 INFO  - jmeter.util.BeanShellTestElement: Third word is:  fox 
    2014/10/08 13:17:37 INFO  - jmeter.util.BeanShellTestElement:  jumped 
    2014/10/08 13:17:37 INFO  - jmeter.util.BeanShellTestElement:  over 
    

    I would recommend using logging all the values via log.info method and examining the output. Since JMeter 2.6 Log Viewer is available and you should be able to see what's happening right in JMeter GUI as:

    Beanshell Logging

    For more Beanshell tips and tricks refer to How to use BeanShell: JMeter's favorite built-in component guide.