FileUtil.java
2.88 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.batch.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import org.springframework.core.io.ClassPathResource;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class FileUtil {
public static StringBuffer readFileToString(String resourceName) {
StringBuffer sb = new StringBuffer();
try {
ClassPathResource resource = new ClassPathResource(resourceName);
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
// br.readLine() 이 null 인지 검사할 때 한번 사용되므로 String 에 먼저 저장해둬야한다.
String s = "";
while ((s = br.readLine()) != null) {
sb.append(s);
}
} catch (Exception e) {
sb.append(e.getStackTrace());
}
return sb;
}
/**
* 파일 마지막 부터 lineCnt행 읽기
* @param resourceName
* @param lineCnt
* @return
*/
public static StringBuffer readFileLastLines(String resourceName, int lineCnt) {
StringBuffer sb = new StringBuffer();
// lineCnt = 50; // test case
// resourceName = "D://logs/localhost_access_log.2019-03-26.txt"; // test case
if(resourceName == null || resourceName.isEmpty()) {
sb.append("파일 경로가 입력되지 않았습니다.");
}else if(lineCnt < 1) {
sb.append("라인갯수가 입력되지 않았습니다.");
}else {
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(resourceName, "r");
long len = rf.length();
for (long i = len - 1; i >= 0; i--) {
rf.seek(i);
char c = (char) rf.read();
if (c == '\n') {
lineCnt--;
if(lineCnt < 0) {
break;
}
}
sb.insert(0, c);
}
/*** TODO : 필요 시 파일 인코딩. utf-8 **/
// sb = new StringBuffer(new String((sb.toString()).getBytes("ISO-8859-1"), "UTF-8"));
} catch (Exception e) {
// e.printStackTrace();
sb = new StringBuffer("유효한 파일경로가 아닙니다.("+resourceName+")");
} finally {
if (rf != null) {
try {
rf.close();
} catch (IOException e) {
// e.printStackTrace();
sb = new StringBuffer("유효한 파일경로가 아닙니다.("+resourceName+")");
}
}
}
}
return sb;
}
public static JsonObject strToJsonObj(String jsonString) {
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
return jsonObject;
}
public static Object strToObj(String jsonString, Class<?> anyClass) {
Gson gson = new Gson();
Object convertedObject = gson.fromJson(jsonString, anyClass);
return convertedObject;
}
public static String objToStr(Object obj) {
Gson gson = new Gson();
String stringObject = gson.toJson(obj);
return stringObject;
}
}