0

I know how to use FileOutputStream to write a stream of bytes into a txt files, and I know also how to write them into separate lines (here I would like to call these lines rows).

I would like to know how to write characters into different columns? Say there is a loop in which we would like to write a number in each row's columns. Each column represents an iteration of an inner loop. The output should look like this:

1 3   4
2   3 5
1 2 3 5
2 5
1 2 3 5

How do I do that?

Trow Way
  • 45
  • 3
seventeen
  • 221
  • 4
  • 11

1 Answers1

1

Text files don't have columns, they are just a stream ("one dimesion array") of characters (actually bytes); it is the UI which shows it like there were lines or as "tables".

If you want to export to Excel, Google "CSV" (coma separated values).

If you want to print to stdout, you may want to Google "pretty print ASCII table".

If you want to do it by hand, I'll suggest you iterate though the data to calculate the width of each column first. Then iterate again and print each column with the width you calculated previously.

List < List <String> > rows;
List < Integer > widths = new ArrayList<>(); 
for(int i = 0; i < rows.size(); ++i) {
   List <Integer> row = rows.get(i);
   for (int j = 0; j < row.size(); ++j) {
       widths.ensureCapasity(j + 1);
       Integer max = widths.get(j);
       if( max == null || max < row.get(j).length()) {
          widths.set(j, row.get(j).length());       
       }
   }
}

Then iterate again using the width to pad the string.

See.

Community
  • 1
  • 1
paulocuneo
  • 89
  • 1
  • 3
  • I did not get it. why do you make it so complicated? I only need two loops, one for rows and one for columns. First it goes to first row, then it starts iterating through another loop based on the length of an input (which will be computed dynamically either through each iteration of outer loop or else) and according to some computation, it will write an integer in any given column of any row. Just like I showed in the question, there might be some empty part as well. – seventeen Nov 08 '15 at 05:12
  • i was considering the cells would have different and variable widths. if width of column is fixed do a double loop and print with padding to fixed size, check the link i posted – paulocuneo Nov 08 '15 at 05:23