-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathCsvFileTemplate.java
More file actions
88 lines (71 loc) · 2.63 KB
/
CsvFileTemplate.java
File metadata and controls
88 lines (71 loc) · 2.63 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package org.prgms.springbootbasic.common.file;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
@Component
@Profile("test")
public class CsvFileTemplate {
private static final Logger log = LoggerFactory.getLogger(CsvFileTemplate.class);
public <T> List<T> read(String path, Function<String, T> mapToObj) {
log.info("read started");
List<T> ret = new ArrayList<>();
File file = new File(path);
if (filePathNotExist(file)){
return ret;
}
log.info("file exists.");
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(path), StandardCharsets.UTF_8) ) ){
String line = br.readLine(); // 한 줄 생략
while((line = br.readLine()) != null) {
ret.add(mapToObj.apply(line));
}
} catch (IOException e) {
log.error("Unable to read the file due to an unexpected error.");
throw new RuntimeException(e);
}
return ret;
}
public <T> void write(String path, List<T> objs, Function<T, String> objToString, String firstLine) {
log.debug("write started");
try (BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(path), StandardCharsets.UTF_8) ) ){
bw.write(firstLine);
bw.newLine();
for (T obj : objs) {
String objToStr = objToString.apply(obj);
bw.write(objToStr);
}
} catch (FileNotFoundException e){
log.error("File is not found.");
throw new RuntimeException("File is not found.");
} catch (IOException e){
log.error("IOException.");
throw new RuntimeException("Writing error occurred.");
}
}
private boolean filePathNotExist(File file) {
try {
if(file.getParentFile().mkdirs()) {
return true;
}
file.createNewFile();
} catch (SecurityException e){
log.error("Security problem occurred.");
throw e;
} catch (IOException e){
log.error("An error occurred during file checking.");
throw new RuntimeException(e);
}
log.info("File directory created.");
return false;
}
}