简体   繁体   中英

Groovy script prevents deletion of files - how to obey it?

I have a technical problem with groovy. Generally speaking I create thread (using TimerTask) which reads all files from specific folder with defined frequency and checks if it contains some specific pattern. Pseudocode:

def startTimer() {
    new TimerTask() {
        int listFilesForFolder(final File folder, int txn) throws IOException {
            String file
            folder.listFiles().each { final File fileEntry ->
                if (fileEntry.isDirectory()) {
                    listFilesForFolder(fileEntry)
                } else {
                    file = fileEntry.getName()
                    try {
                        findTransactionType(folder.toString(), file, txn)
                    } catch (FileNotFoundException e) {
                        e.printStackTrace()
                    }
                }
            }
            tmp = this.amount
            this.amount = 0
            return tmp
        }

        private findTransactionType(String folder, String file, int txn) {
            Pattern p = Pattern.compile("paaaattteeerrrnnn")
            BufferedReader r = new BufferedReader(new FileReader(folder + "\\" + file))
            String line

            while ((line = r.readLine()) != null) {
                Matcher m = p.matcher(line)
                while (m.find()) {
                    m = p.matcher(m.group(0))
                    while (m.find()) {
                        if (m.group(1).contains(txn.toString())) {
                            this.amount++
                        }
                    }
                }
            }
        }
    }, 0, interval * 1000)
}

Nevertheless I need to get ready for situations that someone can delete files from my folder. But during deletion I've got error - cannot acces file becuase it's been using by another program.

How can I obey it? What should I do to freely delete files from folder where my groovy script runs periodically?

Of course it was my fault ;-)

I forgot to close the BufferedReader stream, so I missed r.close() line. Have a nice day:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM