01: /*
02: * SqlServerFormatFileWriter.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.db.exporter;
13:
14: import java.io.BufferedWriter;
15: import java.io.File;
16: import java.io.FileWriter;
17: import java.io.IOException;
18: import java.io.PrintWriter;
19: import workbench.log.LogMgr;
20: import workbench.storage.ResultInfo;
21: import workbench.util.CharacterRange;
22: import workbench.util.FileUtil;
23: import workbench.util.StringUtil;
24: import workbench.util.WbFile;
25:
26: /**
27: * @author support@sql-workbench.net
28: */
29: public class SqlServerFormatFileWriter implements FormatFileWriter {
30: public SqlServerFormatFileWriter() {
31: }
32:
33: public void writeFormatFile(DataExporter exporter,
34: RowDataConverter converter) {
35: ResultInfo resultInfo = converter.getResultInfo();
36: WbFile baseFile = new WbFile(exporter.getFullOutputFilename());
37: String dir = baseFile.getParent();
38: String baseName = baseFile.getFileName();
39: File ctl = new File(dir, baseName + ".fmt");
40: PrintWriter out = null;
41: try {
42: int count = resultInfo.getColumnCount();
43: out = new PrintWriter(new BufferedWriter(
44: new FileWriter(ctl)));
45: out.println("7.0"); // Write bcp version string
46: out.println(Integer.toString(count));
47:
48: int max = 0;
49: // calculate max. column name length for proper formatting
50: for (int i = 0; i < count; i++) {
51: int l = resultInfo.getColumnName(i).length();
52: if (l > max) {
53: max = l;
54: }
55: }
56: max++;
57:
58: String delim = StringUtil.escapeUnicode(exporter
59: .getTextDelimiter(), CharacterRange.RANGE_CONTROL);
60: String nl = StringUtil.escapeUnicode(exporter
61: .getLineEnding(), CharacterRange.RANGE_CONTROL);
62:
63: for (int i = 0; i < count; i++) {
64: String name = resultInfo.getColumnName(i);
65: String col = StringUtil.padRight(name, max);
66: if (name.indexOf(' ') > -1) {
67: col = "\"" + col + "\"";
68: }
69: String pos = StringUtil.formatNumber(i + 1, 4, true);
70: String term = null;
71: if (i < count - 1) {
72: term = delim;
73: } else {
74: term = nl;
75: }
76: out.println(pos + " SQLCHAR 0 0 \"" + term + "\" "
77: + pos + " " + col);
78: }
79: } catch (IOException io) {
80: LogMgr.logError(
81: "SqlServerFormatFileWriter.writeFormatFile()",
82: "Error opening outputfile", io);
83: } finally {
84: FileUtil.closeQuitely(out);
85: }
86: }
87: }
|