forked from Team254/FRC-2019-Public
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReflectingCSVWriter.java
76 lines (69 loc) · 2.15 KB
/
ReflectingCSVWriter.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
package com.team254.lib.util;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentLinkedDeque;
/**
* Writes data to a CSV file
*/
public class ReflectingCSVWriter<T> {
private ConcurrentLinkedDeque<String> mLinesToWrite = new ConcurrentLinkedDeque<>();
private PrintWriter mOutput = null;
private Field[] mFields;
public ReflectingCSVWriter(String fileName, Class<T> typeClass) {
mFields = typeClass.getFields();
try {
mOutput = new PrintWriter(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Write field names.
StringBuilder line = new StringBuilder();
for (Field field : mFields) {
if (line.length() != 0) {
line.append(", ");
}
line.append(field.getName());
}
writeLine(line.toString());
}
public void add(T value) {
StringBuilder line = new StringBuilder();
for (Field field : mFields) {
if (line.length() != 0) {
line.append(", ");
}
try {
if (CSVWritable.class.isAssignableFrom(field.getType())) {
line.append(((CSVWritable) field.get(value)).toCSV());
} else {
line.append(field.get(value).toString());
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
mLinesToWrite.add(line.toString());
}
protected synchronized void writeLine(String line) {
if (mOutput != null) {
mOutput.println(line);
}
}
// Call this periodically from any thread to write to disk.
public void write() {
while (true) {
String val = mLinesToWrite.pollFirst();
if (val == null) {
break;
}
writeLine(val);
}
}
public synchronized void flush() {
if (mOutput != null) {
write();
mOutput.flush();
}
}
}