-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSVWriter.java
78 lines (58 loc) · 1.63 KB
/
CSVWriter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.io.FileWriter;
import java.io.IOException;
public class CSVWriter {
private String fileName;
private String columns[];
private FileWriter writer;
private boolean fileCreated = false;
public CSVWriter (String fileName) throws IOException {
this(fileName, null);
}
public CSVWriter (String fileName, String columns[]) throws IOException {
this.fileName = fileName;
this.columns = columns;
this.generateFile(fileName);
}
public String getFileName() {
return this.fileName;
}
public String[] getColumns() {
return this.columns;
}
public void writeToFile(String values[]) throws IOException {
if (!fileCreated) {
generateFile(this.fileName);
}
//First check if the amount of values given matches the amount of columns. If no columns are given just write whatever is sent.
if (values.length == this.columns.length || this.columns == null) {
this.writeRow(values);
}
}
public void writeStringToFile(String values) throws IOException {
if (!fileCreated) {
generateFile(this.fileName);
}
writer.append(values);
writer.append("\n");
}
public void closeWriter() throws IOException {
this.writer.flush();
this.writer.close();
}
private void generateFile(String fileName) throws IOException {
this.writer = new FileWriter(fileName);
if (columns != null) {
this.writeRow(this.columns);
}
fileCreated = true;
}
private void writeRow(String values[]) throws IOException {
for (int i = 0; i < values.length; i++) {
writer.append(values[i].toString());
if (i < values.length - 1) {
writer.append(";");
}
}
writer.append("\n");
}
}