tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java Scripting > BeanShell > To CSV

To CSV 

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell is a natural scripting language for Java. This requires the library bsh-2.0b4.jar to be in classpath. The following example shows generating a CSV from beanshell script.

File Name  :  
/BEAN_SHELL001/config/tocsv.bsh 
   
sb = new StringBuilder("Name,Age,Hobby");

for (std : students) {
  sb.append("\n").append(std.name).append(",").append(std.age);
  sb.append(",").append(std.hobby);
}

print(sb);
   

File Name  :  
com/bethecoder/tutorials/bean_shell/common/Student.java 
   
package com.bethecoder.tutorials.bean_shell.common;

public class Student {

  private String name;
  private int age;
  private String hobby;

  public Student() {
  }

  public Student(String name, int age, String hobby) {
    super();
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }
  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  
  public boolean isKid() {
    return age < 5;
  }
  
  public String toString() {
    return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]";
  }
}
   

File Name  :  
com/bethecoder/tutorials/bean_shell/ToCSVTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.bean_shell;

import java.io.InputStreamReader;
import java.util.Arrays;

import bsh.EvalError;
import bsh.Interpreter;

import com.bethecoder.tutorials.bean_shell.common.Student;

public class ToCSVTest {

  /**
   @param args
   @throws EvalError 
   */
  public static void main(String[] argsthrows EvalError {
    
    Student student = new Student("Sriram"2"Chess");
    Student student2 = new Student("Sudhakar"29"Painting");
    Student student3 = new Student("Charan"18"Reading books");
    
    Interpreter interpreter = new Interpreter();  
    interpreter.set("students", Arrays.asList(student, student2, student3));
    
    InputStreamReader reader = new InputStreamReader(
        ToCSVTest.class.getClassLoader()
        .getResourceAsStream("tocsv.bsh"));
    
    interpreter.eval(reader);
  }

}
   

It gives the following output,
Name,Age,Hobby
Sriram,2,Chess
Sudhakar,29,Painting
Charan,18,Reading books



 
  


  
bl  br