-
Notifications
You must be signed in to change notification settings - Fork 1
/
IoUtil.java
140 lines (130 loc) · 3.17 KB
/
IoUtil.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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package cn.xanderye.util;
import java.io.*;
/**
* Created on 2020/3/2.
*
* @author XanderYe
*/
public class IoUtil {
/**
* 复制流
* @param in
* @param out
* @return long
* @author XanderYe
* @date 2021/4/20
*/
public static long copy(InputStream in, OutputStream out) throws IOException {
return copy(in, out, 8192);
}
/**
* 复制流
* @param in
* @param out
* @param bufferSize
* @return long
* @author XanderYe
* @date 2021/4/20
*/
public static long copy(InputStream in, OutputStream out, int bufferSize) throws IOException {
if (bufferSize < 0) {
bufferSize = 8192;
}
byte[] bytes = new byte[bufferSize];
int len;
long size = 0L;
while ((len = in.read(bytes)) > 0) {
out.write(bytes, 0, len);
size += len;
out.flush();
}
return size;
}
/**
* 读取byte数组
* @param in
* @return byte[]
* @author XanderYe
* @date 2021/4/20
*/
public static byte[] readBytes(InputStream in) throws IOException {
return readBytes(in, true);
}
/**
* 读取byte数组
* @param in
* @param isClose
* @return byte[]
* @author XanderYe
* @date 2021/4/20
*/
public static byte[] readBytes(InputStream in, boolean isClose) throws IOException {
return read(in, isClose).toByteArray();
}
/**
* 读取outputStream
* @param in
* @param isClose
* @return byte[]
* @author XanderYe
* @date 2021/4/20
*/
public static ByteArrayOutputStream read(InputStream in, boolean isClose) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
copy(in, bos);
} finally {
if (isClose) {
close(in);
}
}
return bos;
}
/**
* 读取socket数据方法
*
* @param inputStream
* @return byte[]
* @author XanderYe
* @date 2019/8/6
*/
public static byte[] readSocket(InputStream inputStream) {
return readSocket(inputStream, null);
}
/**
* 读取socket定长数据方法
*
* @param inputStream
* @return byte[]
* @author XanderYe
* @date 2019/8/6
*/
public static byte[] readSocket(InputStream inputStream, Integer length) {
try {
// 避免获取0的情况
int firstByte = inputStream.read();
length = length == null ? inputStream.available() + 1 : length;
byte[] bytes = new byte[length];
bytes[0] = (byte) firstByte;
inputStream.read(bytes, 1, length - 1);
return bytes;
} catch (IOException e) {
return new byte[0];
}
}
/**
* 关闭流
* @param closeable
* @return void
* @author XanderYe
* @date 2021/4/20
*/
public static void close(Closeable closeable) {
if (null != closeable) {
try {
closeable.close();
} catch (Exception ignored) {
}
}
}
}