BlueStar
BlueStar

Reputation: 411

How to write fields dynamically to a csv file using a tJava

I'm using Talend to extract database field names from the table and write to a csv them after replacing the "_" in field names with " ". I want to have these values against the actual headers.

eg:

|First_Name|Last_Name|
|----------|---------|
|First Name|Last Name|

My job looks similar to following. enter image description here

Code in tJavaRow is as follows:

    for (java.lang.reflect.Field field: 
 input_row.getClass().getDeclaredFields()) {
 String fieldName = field.getName();
 String newFieldName = null;
 newFieldName = fieldName.replaceAll("_", " ");
 context.columnName = newFieldName;
 System.out.println("Field name is " + context.columnName );
     }

How can I get the value of this context variable for each field in csv file? If I directly use it in the tmap it will only have name of the last field as value. tmap I had between tJava and the tFileOutputDelimited.enter image description here

Upvotes: 1

Views: 1776

Answers (1)

Gokul Potluri
Gokul Potluri

Reputation: 262

you cannot change schema as they are treated as declared variables in java code which is generated in backend.

your schema "|First_Name|Last_Name|" is converted into as below:
String First_Name =null;
String Last_Name = null;
So you cannot change those schema column names on fly.

But you can create a record from the column names which you are retrieving from database by using the delimiter you want(lets take comma)

for (java.lang.reflect.Field field : input_row.getClass().getDeclaredFields()) {
    String fieldName = field.getName();
    context.columnName = context.columnName + "," + fieldName.replaceAll("_", " ");
}

And now, before writing your data into a csv file, write this header record in context.columnName into that csv file.
After writing the header record, append your data to that file by checking "Append" check box in tFileOutputDelimitted.

Upvotes: 0

Related Questions