1 package com.github.celldynamics.quimp.utils;
2
3 import java.io.BufferedWriter;
4 import java.io.File;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.io.PrintWriter;
8 import java.nio.file.Path;
9
10 import ij.IJ;
11
12
13
14
15
16
17
18 public class CsvWritter {
19 private PrintWriter pw = null;
20 private Path path;
21
22
23
24 public String delimiter = "\t";
25
26
27
28 public int decPlaces = 4;
29
30
31
32
33
34
35 public CsvWritter() throws IOException {
36 path = File.createTempFile("csvwritter-", ".csv").toPath();
37 pw = new PrintWriter(new BufferedWriter(new FileWriter(path.toFile())), true);
38 }
39
40
41
42
43
44
45
46
47
48 public CsvWritter(Path path, String... header) throws IOException {
49 this.path = path;
50 pw = new PrintWriter(new BufferedWriter(new FileWriter(path.toFile())), true);
51 String h = "";
52 if (header == null || header.length == 0) {
53 return;
54 }
55 int i;
56 for (i = 0; i < header.length - 1; i++) {
57 h = h.concat(header[i]).concat(delimiter);
58 }
59 h = h.concat(header[i]);
60 pw.write(h + "\n");
61 }
62
63
64
65
66
67
68
69 public CsvWritter writeLine(String line) {
70 pw.write(line);
71 appendLine("\n");
72 return this;
73 }
74
75
76
77
78
79
80
81
82 public CsvWritter writeLine(Double... doubles) {
83 appendLine(doubles);
84 appendLine("\n");
85 return this;
86 }
87
88
89
90
91
92
93
94
95
96 public CsvWritter appendLine(String line) {
97 pw.write(line);
98 return this;
99 }
100
101
102
103
104
105
106
107
108
109
110 public CsvWritter appendLine(Double... doubles) {
111 int i;
112 String h = "";
113 for (i = 0; i < doubles.length - 1; i++) {
114 h = h.concat(IJ.d2s(doubles[i], decPlaces)).concat(delimiter);
115 }
116 h = h.concat(IJ.d2s(doubles[i], decPlaces));
117 pw.write(h);
118 return this;
119 }
120
121
122
123
124
125
126 public CsvWritter appendDelim() {
127 pw.write(delimiter);
128 return this;
129 }
130
131
132
133
134
135
136
137 public PrintWriter getPw() {
138 return pw;
139 }
140
141
142
143
144
145
146 public Path getPath() {
147 return path;
148 }
149
150
151
152
153 public void close() {
154 if (pw != null) {
155 pw.close();
156 }
157 }
158
159 }