Writing data collected from Postgres database in a

2019-08-26 21:43发布

问题:

I am new to Java and looking for a way to store data collected from query in a text file on my disk. To be exact I am doing something like --

Select A , B , C from blah_1 , blah_2 where ....

I am using JDBC driver to connect and I am storing the data collected in List<> using RowMapper .

I want the data stored in a text file in this manner -

    A        B        C
    a1       b1       c1
    a2       b2       c2
    .        .        .
    .        .        .

package : "org.apache.poi.ss.usermodel" does something like this but for excel sheets , Is there something similar for text files??

回答1:

You can use String.format which provides you with a number of options for formatting a String, for example...

System.out.println(String.format("%-10s%-10s%-10s", "A", "B", "C"));
for (int index = 0; index < 10; index++) {
    System.out.println(String.format("%-10s%-10s%-10s", "a" + index, "b" + index, "c" + index));
}

Will print out...

A         B         C         
a0        b0        c0        
a1        b1        c1        
a2        b2        c2        
a3        b3        c3        
a4        b4        c4        
a5        b5        c5        
a6        b6        c6        
a7        b7        c7        
a8        b8        c8        
a9        b9        c9 

You can have a look at:

  • Java String Format Examples
  • Complete Printf for Java Format String Specification
  • Java String Format Examples
  • Basic I/O - Formatting

for more details

If you don't know the column widths ahead of time, you will have to pre-calculate them, something similar to the example in Properly aligning Strings on the console

For writing the file you should start with Basic I/O but it might look something like...

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("some file somewhere.txt")))) {
    bw.write(String.format("%-10s%-10s%-10s", "A", "B", "C"));
    bw.newLine();
    for (int index = 0; index < 10; index++) {
        bw.write(String.format("%-10s%-10s%-10s", "a" + index, "b" + index, "c" + index));
        bw.newLine();
    }
} catch (IOException ex) {
    ex.printStackTrace();
}


回答2:

tl;dr

"org.apache.poi.ss.usermodel" does something like this but for excel sheets , Is there something similar for text files??

Yes, the Apache Commons CSV library.

CSVPrinter printer = CSVFormat.RFC4180.withHeader( rs ).print( writer ); // Write header row, using database column header names.
printer.printRecords( rs ); // Write each row of the entire result set.

Apache Commons CSV

The Answer by MadProgrammer works well enough. But if you want, there are tools to help you read or write data to files in tab-delimited or comma-separated-values (CSV) format.

I have used Apache Commons CSV for this purpose. This library is even savvy with ResultSet, so it can directly transfer your data to the file without populating an intervening set of arrays or collection of objects. Indeed, Apache Commons CSV does all the heavy lifting in basically two lines of code.

First line grabs the column names and writes them out to the text file.

CSVPrinter printer = CSVFormat.RFC4180.withHeader( rs ).print( writer ); // Write header row, using database column header names.

Next line loops all the rows of the result set, writing out each column of each row to the text file in CSV format.

printer.printRecords( rs ); // Write each row of the entire result set.

Full example app that creates an in-memory database using H2 Database Engine, inserts some rows, then dumps all the data to a text file in CSV format by calling on the Apache Commons CSV library.

try (
    Connection conn = DriverManager.getConnection( "jdbc:h2:mem:trashme" )
) {
    String sql = "CREATE TABLE " + "abc_" + " (\n" +
                     "  data UUID default random_uuid() , \n" +  // Every table should have a primary key.
                     "  a_ VARCHAR , \n" +                       // Three columns per the Question.
                     "  b_ VARCHAR , \n" +
                     "  c_ VARCHAR \n" +
                     " );";
    try (
        Statement stmt = conn.createStatement() ;
    ) {
        stmt.execute( sql );
    }

    sql = "INSERT INTO abc_ (a_ , b_ , c_ ) VALUES ( ? , ? , ? ) ;";
    try ( PreparedStatement ps = conn.prepareStatement( sql ) ) {
        for ( int i = 1 ; i <= 10 ; i++ ) {
            ps.setString( 1 , "a" + i );
            ps.setString( 2 , "b" + i );
            ps.setString( 3 , "c" + i );
            ps.executeUpdate();
        }
    }

    sql = "SELECT a_ , b_ , c_ FROM abc_ ; ";
    try (
        Statement stmt = conn.createStatement() ;
    ) {
        ResultSet rs = stmt.executeQuery( sql );
        // File
        Path path = FileSystems.getDefault().getPath( System.getProperty( "user.home" ) , "trashme.txt" );
        try (
            BufferedWriter writer = Files.newBufferedWriter( path , Charset.forName( "UTF-8" ) ) ;
        ) {
            final CSVPrinter printer = CSVFormat.DEFAULT.withHeader( rs ).print( writer ); // Write header row, using database column header names.
            printer.printRecords( rs ); // Write each row of the entire result set.
        } catch ( IOException x ) {
            System.err.format( "IOException: %s%n" , x );
        }
    }

} catch ( SQLException eArg ) {
    eArg.printStackTrace();
}

Result when run, new file populated with data.