原来是这个,这个是之前的try catch,包括最后进行关流等操作。
private String getBodyString(final ServletRequest request) throws IOException {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = cloneInputStream(request.getInputStream());
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (reader!=null){
reader.close();
}
}
return sb.toString();
}
JDK7新增的try-with-resource可以改善这一写法
private String getBodyString(final ServletRequest request) throws IOException {
var sb = new StringBuilder();
try (
var inputStream = request.getInputStream();
var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
) {
var line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
而try-with-resource则只是语法糖
实际编译上面代码后:
可以看到高亮行进行了关流
private String getBodyString(ServletRequest request) throws IOException {
StringBuilder sb = new StringBuilder();
try {
ServletInputStream inputStream = request.getInputStream();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
try {
String line = "";
while((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Throwable var9) {
try {
reader.close();
} catch (Throwable var8) {
var9.addSuppressed(var8);
}
throw var9;
}
reader.close();
} catch (Throwable var10) {
if (inputStream != null) {
try {
inputStream.close();
} catch (Throwable var7) {
var10.addSuppressed(var7);
}
}
throw var10;
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException var11) {
var11.printStackTrace();
}
return sb.toString();
}
作者:DATA_MONK