I have a method that fetch folder file . I only read the filename of the file. At the end of my program I delete the file. The problem is there's a time that "Too many open files" error appear.
I found out that the deleted files are still open.
Here are my codes:
Getting file
private File getFile(String fileName,String filetype) {
File dir = new File("./");
File[] foundFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(fileName) && name.endsWith(filetype);
}
});
if(foundFiles.length!=0) {
return foundFiles[0];
}
}
...
File tempFile = this.getFile("versions.sh_",".pid");
String fileName = tempFile.getName();
int startNo = fileName.indexOf("_") + 1;
int endNo = startNo + 5;
pid = fileName.substring(startNo, endNo);
//other logic
Deleting File
if (pidFile != null) {
logger.info("Deleting pidFile file = " + pidFile.toString());
Files.deleteIfExists(pidFile.toPath());
}
Know I want to get rid of the code that open the file but I dont know which part of my code. Btw this program runs on linux.
----- update The .pid file is created by script
#!/bin/bash
SCRIPT_PID=`echo $$`
ME=`basename "$0"`
SCRIPT_DIR=$(pwd)
RESULT_TXT=${SCRIPT_DIR}/${ME}_result.txt
PID_FILE=${SCRIPT_DIR}/${ME}_${SCRIPT_PID}.pid
echo $$ > $PID_FILE
The above code keeps the file/folder open in linux. So i used DirectoryStream
and try-resources
block to implement auto-closable to the used resources.
try (DirectoryStream<Path> paths = Files.newDirectoryStream(Paths.get(base),
path -> path.getFileName().toString().startsWith(fileName) && path.toString().endsWith(filetype))) {
paths.forEach(path -> pathList.add(path));
if (pathList.size() > 0) {
file = pathList.get(0).toFile();
}
}