【问题标题】:Writing data collected from Postgres database in a text file using java使用java将从Postgres数据库收集的数据写入文本文件
【发布时间】:2018-06-09 10:18:02
【问题描述】:

我是 Java 新手,正在寻找一种方法来将从查询中收集的数据存储在磁盘上的文本文件中。确切地说,我正在做类似的事情--

选择 A , B , C 从 blah_1 , blah_2 where ....

我正在使用 JDBC 驱动程序进行连接,并且我正在使用 RowMapper 将收集到的数据存储在 List 中。

我希望以这种方式将数据存储在文本文件中-

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

package : "org.apache.poi.ss.usermodel" 做了类似的事情,但是对于 excel 表格,文本文件有类似的东西吗??

【问题讨论】:

    标签: java postgresql jdbc


    【解决方案1】:

    您可以使用String.format,它为您提供了许多用于格式化String 的选项,例如...

    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));
    }
    

    将打印出来...

    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 
    

    你可以看看:

    更多详情

    如果您不提前知道列宽,则必须预先计算它们,类似于Properly aligning Strings on the console 中的示例

    要编写文件,您应该以 Basic I/O 开头,但它可能看起来像...

    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;博士

      "org.apache.poi.ss.usermodel" 做了类似的事情,但是对于 excel 表格,文本文件有类似的东西吗??

      是的,Apache Commons CSV 库。

      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

      Answer by MadProgrammer 运行良好。但是,如果您愿意,也有一些工具可以帮助您读取或写入 tab-delimitedcomma-separated-values (CSV) 格式的文件。

      我为此使用了Apache Commons CSV。这个库甚至精通ResultSet,因此它可以直接将您的数据传输到文件中,而无需填充一组中间数组或对象集合。事实上,Apache Commons CSV 基本上用两行代码完成了所有繁重的工作。

      第一行获取列名并将它们写入文本文件。

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

      下一行循环结果集的所有行,将每一行的每一列以 CSV 格式写入文本文件。

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

      使用 H2 Database Engine 创建内存数据库的完整示例应用程序,插入一些行,然后通过调用 Apache Commons CSV 库将所有​​数据转储到 CSV 格式的文本文件中。

      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();
      }
      

      运行时的结果,新文件填充了数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-12
        • 1970-01-01
        • 1970-01-01
        • 2016-09-01
        • 2020-11-07
        • 1970-01-01
        相关资源
        最近更新 更多