UpProtocolDataService.java
2.1 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
package com.bsth.service;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.bsth.util.AppProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Hill
*/
public class UpProtocolDataService {
private final static Logger log = LoggerFactory.getLogger(UpProtocolDataService.class);
private static UpProtocolDataService service = new UpProtocolDataService();
private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
private String dir = AppProperties.getUpdir();
private Date cur = new Date();
/**
* 下次切换写文件时间节点
*/
private long nextTime;
private BufferedOutputStream out;
private String fileName;
private UpProtocolDataService() {
File file = new File(dir);
Date now = new Date();
if (!file.exists()) {
file.mkdirs();
}
fileName = sdf.format(now);
nextTime = now.getTime() + 3600000 - now.getTime() % 3600000;
try {
out = new BufferedOutputStream(new FileOutputStream(dir + fileName, true));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
log.error(dir + fileName + "文件未找到");
}
}
public static UpProtocolDataService getInstance() {
return service;
}
public void write(byte[] bytes) throws IOException {
long now = System.currentTimeMillis();
if (now >= nextTime) {
cur.setTime(now);
rollOver(now);
}
out.write(bytes);
}
private synchronized void rollOver(long now) throws IOException {
if (now < nextTime) {
return;
}
BufferedOutputStream os = out;
try {
fileName = sdf.format(cur);
File file = new File(dir + fileName);
out = new BufferedOutputStream(new FileOutputStream(file, true));
nextTime = getNextTime(now);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
log.error(dir + fileName + "文件未找到");
} finally {
os.flush();
os.close();
}
}
private long getNextTime(long now) {
return now + 3600000 - now % 3600000;
}
}