kdev
kdev

Reputation: 291

handling new line in java

i have written this small code

ResultSet rs=stmt.executeQuery(my_query);
ResultSetMetaData md=rs.getMetaData();
int numColumns =md.getColumnCount();

for (int i=1; i<numColumns+1; i++) {
     String columnName = md.getColumnName(i);
     Final+=columnName;
}


while (rs.next()) {
     for (int i=1; i<numColumns+1; i++) {
          String  output=rs.getString(md.getColumnName(i));
          Final+=output;
     }     
}

here i want to add tab space in String columnName = md.getColumnName(i);

and new line after Final+=output;

I have tried \n \t and newLine() but nothing worked properly,

since i want to have the Final string with all the column_names Plus data into one variable Final.

I am able to get that easily into Final but the issue is that its all in one line so i need to add tab space(columnName) between column and line space (Final) between rows. Please suggest.

thanks in advance.

Upvotes: 0

Views: 591

Answers (1)

eumiro
eumiro

Reputation: 212825

ResultSet rs=stmt.executeQuery(my_query);
ResultSetMetaData md=rs.getMetaData();
int numColumns =md.getColumnCount();

String output = md.getColumnName(1);
for (int i=2; i<numColumns+1; i++) {
    output += " " + columnName;
}
output += "\n";

while (rs.next()) {
   output += rs.getString(md.getColumnName(1));
   for (int i=2; i<numColumns+1; i++) {
       output += " " + rs.getString(md.getColumnName(i));
   }
   output +=  "\n";
}

Or you could work with lists. Create a new list at the beginning of each line, add elemenents to it and then at the end of the line join them all with spaces, add a newline and append to output. It would be clearer and more general than my proposed solution.

Upvotes: 2

Related Questions