Problem scenario
In the background code of the blog, the design without database is adopted, and all information is based on the file system. When it comes to traversing some file information, the java.nio.file.files class and files.list are used for traversal. However, for stream methods such as files.list, if the resource is not closed, an error of too many open files
will appear over time.
Solution
Use try with resource
to automatically free resources.
Not improved:
...
Files.list(path).forEach(...)
...
Improved writing:
try (Stream<Path> fileList = Files.list(path)) {
fileList.forEach(...)
} catch (Exception a) {
......
}
In this way, the open files will be automatically closed when using files.list to prevent errors. Similarly, it can also be used on other classes that inherit autoclosable, and subsequent problems will be sorted out.
Conclusion
The efficiency and rationality of the code still need to be considered, otherwise the preliminary test can’t see the problem, and it’s too late to regret for a long time.
Read More:
- An idea to solve Warning move_uploaded_file, failed to open stream in the process of php uploading files
- Solution: vs2017 cannot open header files such as stdio. H main. H
- Solution: when cmake is compiled, “error in configuration process project files may be invalid” appears
- Golang gets the list of files under the folder
- “Error in configuration process project files may be invalid” appears during cmake compilation
- When cmake is compiled, “error in configuration process project files may be invalid” appears
- Ida batch processes virus share samples to obtain ASM files and bytes files
- Error: Projects must list all files or use an ‘include‘ pattern.
- Error resolution-“Error in configuration process, project files may be invalid” appears when Cmake compiles openCV
- npm ERR! Error: EPERM: operation not permitted, open ‘C:\Program Files\nodejs\node_ Solution to cache / xxx
- Vscode compiles multiple files, compiles files in subfolders
- [Solved] IE Browser Upload Files Error: org.apache.tomcat.util.http.fileupload.FileUploadException: Stream ended unexpectedly
- could not open `C:\Program Files\Java\jre1.8.0_191\lib\amd64\jvm.cfg’
- Win10 can’t drag files to open directly
- JMeter can’t open and save files [How to Solve]
- After the installation of vs2017, we can’t find the source files such as windows. H, stdio. H, etc
- FileZilla Server prompts 550 Could not open file for reading when downloading files (illustration)
- Error: ENOENT: no such file or directory, open ‘E:\Program Files\nodejs\tmp\upload_38b32f25bc984333c
- Error: could not open `C:\Program Files\Java\jre1.8.0_211\lib\amd64\jvm.cfg’ (How to Fix)
- Project files may be invalid appears when cmake compiles opencv3.1, and the debug additional dependency of the compiled opencv3.1 is at the end