01: /*
02: * BadfileWriter.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.importer;
13:
14: import java.io.Writer;
15: import workbench.db.TableIdentifier;
16: import workbench.log.LogMgr;
17: import workbench.resource.ResourceMgr;
18: import workbench.util.EncodingUtil;
19: import workbench.util.FileUtil;
20: import workbench.util.StringUtil;
21: import workbench.util.WbFile;
22:
23: /**
24: * A class to write rejected rows into a flat file.
25: *
26: * @author support@sql-workbench.net
27: */
28: public class BadfileWriter {
29: private WbFile badFile;
30: private int badRows = 0;
31: private String encoding = null;
32:
33: /**
34: * Create a new BadFileWriter.
35: *
36: * If fname indicates a directory, the resulting bad file will be name after
37: * the name of the supplied table (@link TableIdentifier#getTableName()} with
38: * the extendsion ".bad" and will be created in specified directory.
39: *
40: * The file will be deleted upon creation of this BadFileWriter but will
41: * not be created unless at leas one rejected row is written.
42: *
43: * @param fname the name of the bad file to be created
44: * @param table the table for which the import is currently running
45: * @param enc the encoding for the output file
46: *
47: * @see #recordRejected(String)
48: */
49: public BadfileWriter(String fname, TableIdentifier table, String enc) {
50: WbFile f = new WbFile(fname);
51: if (f.isDirectory()) {
52: String tname = StringUtil
53: .makeFilename(table.getTableName())
54: + ".bad";
55: this .badFile = new WbFile(fname, tname);
56: } else {
57: this .badFile = f;
58: }
59: this .encoding = enc;
60: this .badFile.delete();
61: }
62:
63: public void recordRejected(String record) {
64: Writer w = null;
65: try {
66: w = EncodingUtil.createWriter(badFile, encoding, true);
67: w.write(record);
68: w.write(StringUtil.LINE_TERMINATOR);
69: badRows++;
70: } catch (Exception e) {
71: LogMgr.logError("BadFileWriter.recordRejected()",
72: "Could not write record", e);
73: } finally {
74: FileUtil.closeQuitely(w);
75: }
76: }
77:
78: public int getRows() {
79: return badRows;
80: }
81:
82: public CharSequence getMessage() {
83: StringBuilder b = new StringBuilder(50);
84: b.append(this .badRows);
85: b.append(' ');
86: b
87: .append(ResourceMgr.getString("MsgCopyNumRowsRejected")
88: + "\n");
89: b.append(ResourceMgr.getFormattedString("MsgCopyBadFile",
90: this.badFile.getFullPath()));
91: return b;
92: }
93: }
|