1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 错误示范
try (OutputStream outputStream = response.getOutputStream()) {
// 读取filename
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {
byte[] buffer = new byte[1024];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer);
}
}
}
// 正确(向 outputStream 写入数据的时候,必须指定相应的 length )
try (OutputStream outputStream = response.getOutputStream()) {
// 读取filename
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {
byte[] buffer = new byte[1024];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
}
|