-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCsvWriter.txt
More file actions
54 lines (45 loc) · 1.15 KB
/
CsvWriter.txt
File metadata and controls
54 lines (45 loc) · 1.15 KB
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
1. What design principles does this program violate?
Single Responsibility by writing in the logic - and thus need to be decoupled
2. Refactor the program to improve its design.
CsvWriter.java
public class CsvWriter {
PrintWriter writer;
public CsvWriter() {
}
public void setPrinter(/*some args to actually select how you want to output*/){
writer = new PrintWriter(System.out);
}
public void write(String[][] lines) {
for (int i = 0; i < lines.length; i++)
writeLine(lines[i]);
}
private void writeLine(String[] fields) {
if (fields.length == 0)
writer.write("\n");
else {
writeField(fields[0]);
for (int i = 1; i < fields.length; i++) {
writer.write(",");
writeField(fields[i]);
}
writer.write("/n");
}
}
private void writeField(String field) {
if (field.indexOf(',') != -1 || field.indexOf('\"') != -1)
writeQuoted(field);
else
writer.write(field);
}
private void writeQuoted(String field) {
writer.write('\"');
for (int i = 0; i < field.length(); i++) {
char c = field.charAt(i);
if (c == '\"')
writer.write.print("\"\"");
else
writer.write.print(c);
}
writer.write('\"');
}
}