1

At present I pull my data from an MS Access database and within a java application I system.out.print it to the console. I used /t to space out the data, however it appears awkwardly. I would like to place it in some kind of table for a more pleasing look. Any help would be great thanks.

          while(rs.next())
      {
          System.out.print(rs.getInt("season_number")+"\t");
          System.out.print(rs.getInt("season_episode_number")+"\t");
          System.out.print(rs.getInt("series_episode_number")+"\t");
          System.out.print(rs.getString("title")+"\t");
          System.out.print(rs.getString("directed_by")+"\t");
          System.out.print(rs.getString("written_by")+"\t");
          System.out.print(rs.getDate("origional_air_date")+"\t");
          System.out.println(rs.getFloat("viewing_figures")+"\t");

      }
   }
Tony Toews
  • 7,850
  • 1
  • 22
  • 27
London Student
  • 895
  • 6
  • 15
  • 22

4 Answers4

7

The best solution in order to straighten your output out will be to use System.out.printf().

Since printf is very similar to C' printf, you can use control characters in order to format the output. Like this:

System.out.printf( "%-3.2d %-20.20s\n", rs.getInt("season_number"), rs.getString("title") );

Check this link out.

Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47
6

I am new to Java and as part of my efforts to learn it as well as using an IDE, Javadoc, version control, licensing, open sourcing etc. I wrote a simple utility class DBTablePrinter which prints rows from a given table or java.sql.ResultSet to standard out, formatted to look like a table with rows and columns with borders. I hope it will be useful to someone.

Here is the link to the code repo at GitHub: https://github.com/htorun/dbtableprinter

And here is the basic usage:

// Create a connection to the database
Connection conn = DriverManager.getConnection(url, username, password);

// Just pass the connection and the table name to printTable()
DBTablePrinter.printTable(conn, "employees");

It should print something like this:

Printing 10 rows from table(s) EMPLOYEES
+--------+------------+------------+-----------+--------+-------------+
| EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME | GENDER |  HIRE_DATE  |
+--------+------------+------------+-----------+--------+-------------+
|  10001 | 1953-09-02 | Georgi     | Facello   | M      |  1986-06-26 |
+--------+------------+------------+-----------+--------+-------------+
|  10002 | 1964-06-02 | Bezalel    | Simmel    | F      |  1985-11-21 |
+--------+------------+------------+-----------+--------+-------------+
    .
    .

I thank everyone contributing to this question and to stackoverflow.com in general. Your answers helped me a lot and still helping.

Hami Torun
  • 543
  • 4
  • 6
3

I whipped up a TablePrinter class that might be useful to you

Main method snippet:

TablePrinter table = new TablePrinter("MyTest","OtherTest","SillyColumn");
table.addRow("ABC","DEF","GHIJKLMNOPQRSTUVWXYZ");
table.addRow("This is a test","of the","TablePrinter class");

table.print();

And the results:

C:\junk>javac TablePrinter.java

C:\junk>java TablePrinter
TablePrinter test driver
| MyTest         | OtherTest | SillyColumn          |
-----------------------------------------------------
| ABC            | DEF       | GHIJKLMNOPQRSTUVWXYZ |
| This is a test | of the    | TablePrinter class   |


C:\junk>

The class:

import java.util.ArrayList;
/**
 * The table printer classes takes a matrix of data and prints it.
 */
class TablePrinter {

    /**
     * The row class represents one row of data.
     * Yes, it's just a wrapper for String[], but it helps
     * keep it simple.
     */
    private static class Row {
        String[] data;
        Row(String[] v) { data = v; }
    }

    /**
     * Contains column header and max width information
     */
    private static class Col {
        String name;
        int maxWidth;
    }

    // matrix information
    Col[] cols;
    ArrayList<Row> rows;

    /**
     * Constructor - pass in columns as an array, or hard coded
     */
    public TablePrinter(String... names) {
        cols = new Col[names.length];
        for(int i = 0; i < cols.length; i++) {
            cols[i] = new Col();
            cols[i].name = names[i];
            cols[i].maxWidth = names[i].length();
        }

        rows = new ArrayList<Row>();
    }

    /**
     * Adds a row - pass in an array or hard coded
     */
    public void addRow(String... values) {
        if(values.length != cols.length) {
            throw new IllegalArgumentException("invalid number of columns in values");
        }

        Row row = new Row(values);
        rows.add(row);
        for(int i = 0; i < values.length; i++) {
            if(values[i].length() > cols[i].maxWidth) {
                cols[i].maxWidth = values[i].length();
            }
        }
    }

    /**
     * Helper method to make sure column headers and 
     * row information are printed the same
     */
    private void print(String v, int w) {
        System.out.print(" ");
        System.out.print(v);
        System.out.print(spaces(w - v.length()));
        System.out.print(" |");
    }

    /**
     * Ugly, poorly documented print method.
     * All pieces of production code should have some
     * methods that you have to decipher. This fulfils that requirement.
     */
    public void print() {

        System.out.print("|");
        for(Col col : cols) {
            print(col.name, col.maxWidth);
        }
        System.out.println("");
        int numDashes = cols.length*3 + 1;
        for(Col col : cols) numDashes += col.maxWidth;
        // TODO make columns have + instead of -
        System.out.println(dashes(numDashes)); 
        for(Row row : rows) {
            System.out.print("|");
            int i = 0;
            for(String v : row.data) {
                print(v,cols[i++].maxWidth);
            }
            System.out.println("");
        }
        System.out.println("");
    }

    // print a specific number of spaces for padding
    private static String spaces(int i) {
        StringBuilder sb = new StringBuilder();
        while(i  --> 0) sb.append(" ");
        return sb.toString();
    }

    // print a specific number of dashes
    private static String dashes(int i) {
        StringBuilder sb = new StringBuilder();
        while(i  --> 0) sb.append("-");
        return sb.toString();
    }

    // test driver
    public static void main(String[] args) {
        System.out.println("TablePrinter test driver");

        TablePrinter table = new TablePrinter("MyTest","OtherTest","SillyColumn");
        table.addRow("ABC","DEF","GHIJKLMNOPQRSTUVWXYZ");
        table.addRow("This is a test","of the","TablePrinter class");

        table.print();
    }

}
corsiKa
  • 81,495
  • 25
  • 153
  • 204
1

I would suspect there are very few practical applications for large amounts of console output, so I wouldn't worry too much about formatting.

If you're dead set on it, however... well, if you know the max length of each field, you can simply pad each element with spaces to its maximum length.

Edit: This might be a little too much help for a homework but since it's a peripheral issue, here's an example:

private String pad(String value, int maxLength){
    String retVal = value;
    int remainder = maxLength - value.length();
    for (int i = 0; i < remainder; i++){
        retVal += " ";
    }
    return retVal;
}

You could optimize that with StringBuilder for large data sets, but that's the gist of it.

Riggy
  • 1,347
  • 1
  • 14
  • 26
  • Hi Riggy, Its for uni coursework. Its really just asthetical to try and stand out a little. I shall need to do somthing simlar for outputing from a servlet to a browser later. Thanks! – London Student Mar 29 '11 at 16:45
  • Well, in a browser, you'll have CSS and/or HTML tables. But for console, it should be simple enough to just write a Pad() method that takes the max length of a field and the DB value as params, determine the length of the param and then fill out the rest with spaces. – Riggy Mar 29 '11 at 16:48