当前位置:网站首页>try with resource
try with resource
2022-06-25 17:01:00 【Four questions and four unknowns】
preface
Recently, you need to count the information of a field in a log , The format of the log is as follows , It is necessary to count some regular log records , Manual statistics are too troublesome , So write a read by yourself log File and count the total number and the average number of alarms per second , The code is as follows .
2021-06-17 19:05:23.865 ...
2021-06-17 19:05:24.869 ...
2021-06-17 19:05:24.860 ...
2021-06-17 19:05:23.898 alarm to list for xxx: ...
2021-06-17 19:05:23.985 alarm to list for xxx: ...
2021-06-17 19:05:23.999 alarm to list for xxx: ...
......( Omit , In fact, each line of log will have time format data )
2021-06-17 19:06:45.125 alarm to list for xxx: ...
package com.hust.zhang.trywithresource;
import java.io.*;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
public class FileHandler {
private static final String inputFilePath = "/Users/kaizhang/test/input.log";
private static final String outputFilePath = "/Users/kaizhang/test/output.txt";
private static final String fixedSubString = "alarm to list for xxx";
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(inputFilePath)));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
String line;
int count = 0;
String startTime = "";
String endTime="";
while ((line = reader.readLine()) != null) {
if(Objects.equals(count, Integer.valueOf(0))){
startTime = line.substring(0, 23);
}
if (line.contains(fixedSubString)){
count ++;
endTime = line.substring(0, 23);
}
}
int res = average(startTime, endTime, count);
writer.write(" The number of statistics per second is :"+res);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Find the average number of alarms per second
* @param startTime
* @param endTime
* @param count
* @return
*/
private static int average(String startTime, String endTime, int count) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime startDate = LocalDateTime.parse(startTime, formatter);
LocalDateTime endDate = LocalDateTime.parse(endTime, formatter);
Duration period = Duration.between(startDate, endDate);
long second = period.getSeconds();
return count/(int)second;
}
}The main reason is that there is too much log data , Manual statistics are too time-consuming , As long as there is regular data , We can think of ways to be lazy and make statistics . But it uses try with resource This syntax sugar simplifies the code , There is no need to release IO The process of flow , If not , We usually pass try-catch-finally The statement block releases resources at the end . Here is a brief introduction try with resource.
Introduce
try-with-resources yes JDK 7 A new exception handling mechanism in , It can be easily closed in try-catch Resources used in statement blocks . So called resources (resource) After the program is completed , Objects that must be closed .try-with-resources Statement ensures that each resource is closed at the end of the statement . All implemented java.lang.AutoCloseable Interface ( among , It includes the realization of java.io.Closeable All objects of ), Can be used as a resource .
actual combat
Write a simple example , Write a first Connection Class implementation AutoCloseable Interface , as follows ,
public class Connection implements AutoCloseable {
public void sendData() {
System.out.println("send data ......");
}
@Override
public void close() throws Exception {
System.out.println("close connection ......");
}
}Then write the test class TryWithResource
public class TryWithResource {
public static void main(String[] args) {
try (Connection con = new Connection()) {
con.sendData();
} catch (Exception e) {
e.printStackTrace();
}
}
}Run it , give the result as follows , You will find the use of try-with-resource After grammar sugar , After sending data , It will automatically execute AutoCloseable Interface close() Method , Not only is the code more concise , And don't worry about forgetting to release IO Resources lead to waste of system resources ( Include buffer、File descriptor table、Open file table、I-node table And so on , These will not be JVM The system resources recycled by the garbage collection mechanism of )

Version evolution
try-with-resources Since it is JDK 7 A new exception handling mechanism in , Let's take a look at JDK 7 What has changed in the beginning , After all, I know the context to better use it .
Java SE 7 standard
For example, we write a method to read the contents of a file ,
package com.hust.zhang.trywithresource;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReadDate {
public static void main(String[] args) throws IOException {
String inputFilePath = "/Users/kaizhang/test/input.log";
List<String> data1 = readData(inputFilePath);
data1.stream().forEach(System.out::println);
}
private static List<String> readData(@NotNull String inputPath) throws FileNotFoundException {
List<String> strings = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(new File(inputPath)));
try (BufferedReader br = reader) {
for (;;) {
String line = br.readLine();
if (line == null)
break;
strings.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return strings;
}
}Java SE 9 standard
stay Java SE 7 in , If a resource is final Or equivalent to final Variable , So at try Declare resources in a statement block br, And then you can use it try-with-resource Declared resource variables . stay Java SE 9 There is no need to try-with-resources Statement to declare a new variable .
package com.hust.zhang.trywithresource;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReadDate {
public static void main(String[] args) throws IOException {
String inputFilePath = "/Users/kaizhang/test/input.log";
List<String> data1 = readData(inputFilePath);
data1.stream().forEach(System.out::println);
}
private static List<String> readData(@NotNull String inputPath) throws FileNotFoundException {
List<String> strings = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(new File(inputPath)));
try (reader) {
for (;;) {
String line = br.readLine();
if (line == null)
break;
strings.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return strings;
}
}In fact, there are only minor changes , Is in the try There is no need to redeclare the resource before using it . It's now JDK 17 Version of the , It is up to us to explore the changes in the future .
summary
Like above from JDK 7 To JDK 9 In fact, the change is not big , And we usually use IO Resources are usually directly in try-with-resource Statement . And in the back JDK 8 Introduced Stream The concept of flow , add Files Class etc. , Greatly simplifies reading IO The action of flow , You can see Files.readAllLines() Methods are also used try-with-resource This grammar , Using some tool classes to complete the required functions makes the code more readable and elegant .
package com.hust.zhang.trywithresource;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReadDate {
public static void main(String[] args) throws IOException {
String inputFilePath = "/Users/kaizhang/test/input.log";
List<String> data = readData(inputFilePath);
data.stream().forEach(System.out::println);
}
private static List<String> readData(@NotNull String inputPath) throws IOException {
Path path = Paths.get(inputPath);
Stream<String> lines = Files.readAllLines(path).stream().filter(line->!line.isEmpty());
return lines.collect(Collectors.toList());
}
}
Reference link :
1、https://www.oracle.com/technical-resources/articles/java/trywithresources.html
2、Java 9 The improved try-with-resources | Novice tutorial (runoob.com)
边栏推荐
- uniapp实现图片(单张/多张)预览
- Xshell connecting VMware virtual machines
- This latest research has revealed two secrets of cloudy development
- Optimization of lazyagg query rewriting in parsing data warehouse
- Redis系列——概述day1-1
- 【機器學習】基於多元時間序列對高考預測分析案例
- Why does MySQL limit affect performance?
- 3年,我是如何涨薪到20k?
- 1-8file sharing in VMWare
- 剑指 Offer II 014. 字符串中的变位词 滑动窗口
猜你喜欢

Day_ thirteen

Day_ twelve

Babbitt yuan universe daily recommendation: three players holding "tens of millions" of collections have revealed the "three routines" of the digital collection market

六大专题全方位优化,阿里巴巴性能优化小册终开源,带你直抵性能极致

Ten thousand volumes - list of Dali wa

How to view the change trend of cloud database from the behind of the launch of tidb to Alibaba cloud

Xshell connecting VMware virtual machines

Kalman filter meets deep learning: papers on Kalman filter and deep learning

【机器学习】基于多元时间序列对高考预测分析案例

项目经理在项目中起到的作用
随机推荐
卡尔曼时间序列预测
[100 questions of Blue Bridge Cup intensive training] scratch command mobile Blue Bridge Cup scratch competition special prediction programming question intensive training simulation exercise question
WPF development essays Collection - ECG curve drawing
et al和etc区别
Xshell connecting VMware virtual machines
Ten thousand volumes - list of Dali wa
根据先序遍历和中序遍历生成后序遍历
Kalman filter meets deep learning: papers on Kalman filter and deep learning
How did I raise my salary to 20k in three years?
The art of code annotation. Does excellent code really need no annotation?
这些老系统代码,是猪写的么?
Unity技术手册 - 干扰/噪音/杂波(Noise)子模块
剑指 Offer II 014. 字符串中的变位词 滑动窗口
tasklet api使用
Perfect shuffle problem
Uniapp to preview pictures (single / multiple)
深入浅出对话系统——自己实现Transformer
Read mysql45 - a simple understanding of global locks and table locks
FreeRTOS内核时钟不对的问题解决
Redis Series - Overview day1 - 1