将SQL查询结果写入csv文件:不完整的行

时间:2014-03-20 14:16:19

标签: java sql csv

我正在尝试在csv文件中编写一些查询结果。

我认为它工作正常,直到我看到文件的最后一行写完之后:

值; nettingNodeData; BLE57385; CVAEngine; BLE; 4 ;; BDR; NA; ICE ;; RDC ;; CVAEngine ;; 4841263; RDC 价值; ne

我写文件的部分:

public int getLeNodes(String runId, File file) {
    Connection connect = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    int lines = 0;

    try {
        connect = newConnection();
        ps = connect.prepareStatement(HIER_NTT.replace("?", runId));
        ps.setFetchSize(1500);
        rs = ps.executeQuery();

        lines += nnpw.writeCore(file, rs);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(rs, ps, connect);
    }
    return lines;
}

public int writeCore(File file, ResultSet rs) throws FileNotFoundException, IOException {
    int count = 0;
    try {
        BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCount = rsmd.getColumnCount();

        while (rs.next()) {
            for (int col = 1; col <= colCount; col++) {
                try {
                    String val = rs.getString(col);
                    if (rs.wasNull()) {
                        val = "";
                    }
                    output.append(val);
                } catch (ArrayIndexOutOfBoundsException e) {
                    String dec = rs.getBigDecimal(col).toPlainString();
                    System.err.println(String.format("%s %d %s %s %d %s %d", rs.getString(1), col,
                            rsmd.getColumnTypeName(col), file, count, dec, dec.length()));
                    output.append(dec);
                }
                if (col < colCount) {
                    output.append(";");
                }
            }
            output.newLine();
            count++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return count;
}

和SQL(HIER_NTT):

select 'value', 'nettingNodeData', 'BLE' || d.deal_numadm, 
'CVAEngine', 'BLE', '', (1-ntt.lgd_cp), '', 'BDR', 'NA', 'ICE', '', 'RDC', '',
'CVAEngine', '', d.ntt_id, 'RDC' from ntt ntt 
join deals d on d.ntt_id = ntt.ntt_id and d.deal_scope='Y' 
join dt_runs r on r.run_id = ntt.run_id 
where r.run_id=? and d.deal_numadm!=0 group by d.deal_numadm, d.deal_nummas, d.ntt_id, ntt.lgd_cp

那么,为什么我的文件会像这样突然结束?

1 个答案:

答案 0 :(得分:1)

完成写入文件后,您应该致电output.close()。当java进程退出时,缺少的输出可能仍在缓冲区中